我正在尝试修复一些大量使用 vector 的代码,并且有一些看起来像这样的循环:
for (int t=0;t<T;t++){
std::vector<double> vect;
for (int i=0;i<MAX;i++){
double value;
vect.push_back(value);
}
/*....*/
}
我或多或少知道如何通过在外部迭代中重用相同的 vector 来改进这一点,但是在这样做时我发现在调用 std::vector::clear
"the vector capacity is not guaranteed to change" 时,而我实际上希望容量能够保证不会改变。也许我只是误解了 cplusplus.com 上写的内容。但是,我的问题是:
如何在不改变容量的情况下清除 vector ?
我应该在 clear
之后调用 reserve
以确保容量相同吗?
PS:为了清楚起见,我想将上面的代码重写为
std::vector<double> vect;
vect.reserve(MAX);
for (int t=0;t<T;t++){
for (int i=0;i<MAX;i++){
double value;
vect.push_back(value);
}
/*....*/
vect.clear();
}
即。我仍然想通过 push_back
填充它,我担心 clear()
会改变 vector 的容量。
最佳答案
cppreference明确表示 vector 的容量不变。
来自 cppreference(粗体强调它是我自己的):
void clear();
Removes all elements from the container. Invalidates any references, pointers, or iterators referring to contained elements. May invalidate any past-the-end iterators.
Leaves the capacity() of the vector unchanged.
编辑
正如 Dmitry Kuznetsov 在评论中指出的那样,standard没有提到容量:
expression:
a.clear()
return type:
void
Assertion/note pre-/post-condition: Destroys all elements in a. Invalidates all references, pointers, and iterators referring to the elements of a and may invalidate the past-the-end iterator.post: a.empty() returns true.
Complexity: Linear.
关于c++ - 如何清除 vector 但保持其容量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37027674/