Home > Mobile >  vector size changes after push_back()
vector size changes after push_back()

Time:07-06

I am not sure why the .size() of a vector<string> (10) below is changing from 10 to 20 after .push_back(string) on it. I would assume it should remain the same.

int main() {

   vector<string> StrVec(10);
   vector<int>     intVec(10);
   iota(intVec.begin(), intVec.end(), 1);

   cout << "StrVec.length = " << StrVec.size() << endl;

   for (int i : intVec)
   {
       StrVec.push_back(to_string(i));
   }

   cout << "StrVec.length = " << StrVec.size() << endl;

   return 0;
}

Output:

StrVec.length = 10
StrVec.length = 20

CodePudding user response:

When you write vector<string> StrVec(10);, it initializes StrVec with 10 default-initialized string elements. Then, each push_back() pushes a new element to StrVec while iterating over intVec, thus arriving at 20 elements.

If you only wanted to pre-allocate memory (but not have any elements), you might consider using this instead:

vector<string> StrVec;
StrVec.reserve(10);

If you'd like to access elements of an already allocated vector, you might use StrVec[i], where i is the index. Note that you might not index past the end of the vector.

  • Related