vector<> and erase, insert

Want to use erase(), insert() instead of *iterator = value:
It hangs the pc ;)

1
2
3
4
5
6
7
8
9
10
11
void replace(vector<string>& vec, string old, string replacement) {
	vector<string>::iterator v = vec.begin();
	while (v != vec.end()) {
		if (*v == old) {
			*v = replacement;
			//vec.erase(v);
			//vec.insert( vec.begin(), replacement);
		}
		v++;
	}
}
vec.erase(v) invalidates v (and all iterators that comes after v) so you cannot safely continue using it. The erase function returns an iterator to the position after the erased element that you can keep using instead. That is the position where you want to insert the replacement (assuming you want the same behaviour as before). The insert function can also invalidate iterators. It returns an iterator to the newly inserted element so keep using that iterator.

1
2
3
4
5
6
7
8
9
10
11
void replace(vector<string>& vec, string old, string replacement) {
	vector<string>::iterator v = vec.begin();
	while (v != vec.end()) {
		if (*v == old) {
			//*v = replacement;
			v = vec.erase(v);
			v = vec.insert(v, replacement);
		}
		v++;
	}
}


Note that all this can very easily be written using std::replace from the <algorithm> header.

 
std::replace(vec.begin(), vec.end(), old, replacement);

https://en.cppreference.com/w/cpp/algorithm/replace
Last edited on
thanks a million lot!! to you peter, great knowledge
Topic archived. No new replies allowed.