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;
}
*/
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.