The iterator invalidation rules Problem.

can an iterator be valid after insertion in vector ?

i tried this code :

1
2
3
4
5
6
7
8
9
10
11
12
 vector<int> vec1 = { 1,2,3,4,6,56 };
	vec1.reserve(20);
	auto offend = vec1.end();
	auto beg = vec1.begin();
	auto last = offend - 1;
	auto curr = beg + 4;
	
	print<vector<int>>(vec1) << '\n';
	cout << "The First Element is : " << *beg << "  The Last Element is : " << *last << "  The Selected Element is " << *curr << '\n';
	vec1.insert(vec1.begin(), 17);
	cout << "The First Element is : " << *beg << "  The Last Element is : " << *last << "  The Selected Element is " << *curr << '\n';
	


and it was compiled well.

and i read that every iterator , pointer and reference after the inserted Element is invalid
and Every iterator and pointer , reference is invalid if the vector is reallocated

so (curr) must be invalid! because there is no reallocation but it was just incremented.

did i understand wrong ?
Last edited on
You understood correctly.

Keep in mind, however, that when you access an invalid iterator, it might contain the value that you expect, or it might not. It might contain the right data every time in one program and then when you make a change to the code or compiler options, it doesn't.

Put another way, "invalid" does not mean "alway incorrect." Sometimes it has the expected value, but that's just coincidence. It might help to think of the iterator as "unreliable" instead. You can't rely on the iterator having the expected value.
Thanks for replying @dhayden.

I think it's now clear 😆

Topic archived. No new replies allowed.