Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterator returns garbage [duplicate]

Cannot figure out where I went wrong. As I understand, this code should return "1, 2, 3" but I get the following. I need the vector and its iterators declared globally because I am passing the vector to functions in my actual code and need to update the iterators as well in some functions. Any help is appreciated!

#include <iostream>
#include <vector>

using namespace std;

vector<float> grid;
vector<float>::iterator gridPtr;

int main()

{
  grid.push_back(1);
  grid.push_back(2);

  gridPtr = grid.begin();

  grid.push_back(3);

  cout << "gridPtr: " << *gridPtr << endl;

  gridPtr++;

  cout << "gridPtr: " << *gridPtr << endl;

  gridPtr++;

  cout << "gridPtr: " << *gridPtr << endl;
}

This returns:

gridPtr: 2.62257e-33
gridPtr: 2
gridPtr: 0
like image 408
bcf Avatar asked Oct 19 '25 14:10

bcf


1 Answers

push_back() may invalidate all iterators. Namely, if it has to reallocate the backing store, all existing iterators become invalidated.

If you know ahead of time how many elements you're going to push, you can use reserve() to preallocate the necessary memory, which will prevent push_back() from reallocating (and thus invalidating iterators).

like image 75
Lily Ballard Avatar answered Oct 22 '25 02:10

Lily Ballard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!