迭代器失效解决办法

题目:利用迭代器去掉字符串"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的情况。

猜你喜欢

转载自blog.csdn.net/qq_41877184/article/details/89856347
今日推荐