hello,
when i use vector to store some data, i usually access to this data by the pointer of the vector's first entry. because it it faster than the at() method. but i realize that when i insert a block of data, say an array to the end of vector, the first entry's pointer changes. this may be realated to stack stuff, but if i add the array one element at a time by push_back, first pointer does not change. so why is that? should i worry about using a pointer to access the elements?
here is a sample code for those who wants to check out:
int arrayLen = 500000;
vector<int> vint = vector<int>(2000,0);
int * firstEntry = &vint[0];
int * iarray = new int[arrayLen];
for(int i = 0; i< arrayLen; i++)
{
iarray[i] = i;
}
vint.insert(vint.end(),iarray,iarray+arrayLen);
cout << firstEntry << "," << &vint[0] << endl; // They ar not equal;
// reset the vector
vint.clear();
vint.resize(2000,0);
firstEntry = &vint[0];
for(int i = 0; i< arrayLen; i++)
{
vint.push_back(iarray[i]);
if(firstEntry != &vint[0])
cout << firstEntry << "," << &vint[0] <<","<< i << endl;
}// nothing is written
cout << firstEntry << "," << &vint[0] << endl; // now they are equal;