1

I seem to be having a problem displaying an item in a vector with an iterator. Possibly, I just need another set of eyes to look at it.

vector<string> tempVector;
vector<string>::iterator it;


it = tempVector.begin();
tempVector.push_back("1");
cout << *it;

I know this isn't the full code, but it's the only portion running. The output is a segfault. doesn't the iterator point to the beginning of the vector? I was expecting to get "1" to cout.

Ci3
  • 4,632
  • 10
  • 34
  • 44

1 Answers1

5

The call to vector::reserve() invalidates all existing iterators if it happens to require reallocation.

To quote the C++ standard, 23.3.6.3[vector.capacity]

Reallocation happens at this point if and only if the current capacity is less than the argument of reserve(). [...] Reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence.

EDIT: After the edit, you have a call to vector::push_back(), which also invalidates all iterators if it requires reallocation. Iterator invalidation rules may be helpful.

Community
  • 1
  • 1
Cubbi
  • 46,567
  • 13
  • 103
  • 169
  • @ChrisHarris, "invalidates all iterators" means if you try to use an iterator you created previously, you're likely to seg fault. – Mark Ransom Sep 20 '12 at 02:47