Change vector first pointer

When I use a vector to store some data, I usually access this data using the pointer of the first record of the vector. because it is faster than the at () method. But I understand that when I insert a data block, say an array at the end of a vector, the first pointer to the record changes. This can be implemented for the stack, but if I add an array one element at a time using push_back, the first pointer will not change. So why is that? Should I worry about using a pointer to access items?

Here is a sample code for those who want to check:

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;
+3
source share
3 answers

std::vector . , , , , . , ( , ). , .

, , . , push_back() , , vint.capacity() == vint.size(). , & vint [0] ( & vint.at(), ), .

, , , , () ( ). , - ,

vint.reserve(vint.size() + 2000);
for(int i=0; i<2000; ++i) {
    vint.push_back(i);
}

,

for(int i=0; i<2000; ++i) {
    vint.reserve(vint.size() + 1);
    vint.push_back(i);
}

, .

+4

. [] at(), , , : . : , " " STL ( , Visual ++), .

, , reserve().

+2

reserve() .

Then get your "first pointer", which should not change if you have correctly reserved the correct number of elements.

But why don't you use it begin()? Operators *and ->are working on it, you know ...

+1
source

Source: https://habr.com/ru/post/1771270/


All Articles