Does std::vector change its address? How to avoid
Posted
by kunigami
on Stack Overflow
See other posts from Stack Overflow
or by kunigami
Published on 2010-03-15T13:26:07Z
Indexed on
2010/03/15
13:29 UTC
Read the original article
Hit count: 170
Since vector elements are stored contiguously, I guess it may not have the same address after some push_back's , because the initial allocated space could not suffice.
I'm working on a code where I need a reference to an element in a vector, like:
int main(){
vector<int> v;
v.push_back(1);
int *ptr = &v[0];
for(int i=2; i<100; i++)
v.push_back(i);
cout << *ptr << endl; //?
return 0;
}
But it's not necessarily true that ptr contains a reference to v[0], right? How would be a good way to guarantee it?
My first idea would be to use a vector of pointers and dynamic allocation. I'm wondering if there's an easier way to do that?
PS.: Actually I'm using a vector of a class instead of int, but I think the issues are the same.
© Stack Overflow or respective owner