[英]vector size changes after push_back()
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.我不确定为什么下面的
vector<string> (10)
的.size()
() 在.push_back(string)
之后从 10 变为 20。 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
When you write vector<string> StrVec(10);
当你写
vector<string> StrVec(10);
, it initializes StrVec
with 10 default-initialized string
elements. ,它用 10 个默认初始化的
string
元素初始化StrVec
。 Then, each push_back()
pushes a new element to StrVec
while iterating over intVec
, thus arriving at 20 elements.然后,每个
push_back()
在迭代StrVec
时将一个新元素推送到intVec
,从而达到 20 个元素。
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.如果您想访问已分配向量的元素,您可以使用
StrVec[i]
,其中i
是索引。 Note that you might not index past the end of the vector.请注意,您可能不会索引超出向量的末尾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.