c++ - 如何清除 vector 但保持其容量?

标签 c++ vector

我正在尝试修复一些大量使用 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/

相关文章:

c++ - 在 C++ 中使用访问器引用 vector 进行迭代

c++ - VC++ Debug模式:批量编辑 std::vector<int> 值?

c++ - 使用 ifstream 打开文件后的 Cin.get()

r - 使用 purrr :map 将向量映射到键值列表

c++ - 使用 vector::back() 修改 vector 元素

c++ - 我如何告诉一个 wstring 我正在喂它的字符串已经是一个 wstring?

c++ - 在编译时强制执行正确的状态转换

c++ - 当 std::vector 增长时,其中元素的地址是否不再有效?

C++: STL: vector: remove: 析构函数调用

c++ - Vectors 2D 首次使用