迭代器失效解決辦法

題目:利用迭代器去掉字符串"1 2 3"之間的空格。

錯誤代碼:


#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
string a="1 2 3";
void Del_blank(string& str){
	for(string::iterator it=str.begin();it!=str.end();it++){
		if(*it==' '){
			str.erase(it);
		}
	}
}
int main(){	
	Del_blank(a);
	cout<<a;
	return 0;
}

原因:迭代器經過一次刪除操作就已經失效了。

解決方案:

#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
string a="1 2 3";
void Del_blank(string& str){
	for(string::iterator it=str.begin();it!=str.end();){
		if(*it==' '){
			it=str.erase(it);
		}else{
			it++;
		}
	}
}
int main(){	
	Del_blank(a);
	cout<<a;
	return 0;
}

說明:string.erase()其實已經解決了這個問題,當使用erase()時,將返回一個指向下一個地址的迭代器,因此我們需要注意判斷迭代器+1的情況。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章