Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

vector size changes after push_back()

I am not sure why the .size() of a vector (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;
}    

*/

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Output:

StrVec.length = 10
StrVec.length = 20

>Solution :

When you write vector<string> StrVec(10);, it default-initializes a vector of strings with 10 elements. Then, each push_back() pushes one element to it while iterating over intVec, thus arriving at 20 elements.
If you only wanted to preallocate memory (but not have any elements), you might consider using:

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading