c++ - std::vector 何时重新分配其内存数组?

标签 c++ stl vector

我找不到任何能给出明确答案的东西。我只是好奇 std::vector 是否仅在绝对必须或将在预期中提前重新分配时才重新分配其内部数组(可以这么说)。

例如:

std::vector<int> myVector;
for (int i = 0; i < 1000; ++i) myVector.push_back(i);

cout << myVector.size() << '\n'      // Gives 1000 as expected
     << myVector.capacity() << endl; // Gives 1024 which makes sense

如果我继续添加元素,我添加的接下来的 24 项中的一项是否会改变容量,或者只有在我放入第 25 项后才会重新分配?

注意:

我确实在 Linux 下使用 gcc 4.4.3 进行了测试,但似乎重新分配是“按需”完成的,但我很好奇我是否只是幸运,或者是否有什么地方表明这是预期的行为。

最佳答案

来自 C++ 标准 23.2.4.2:

size_type capacity() const;

Returns: The total number of elements that the vector can hold without requiring reallocation.

也来自标准

Notes: Reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. It is guaranteed that no reallocation takes place during insertions that happen after a call to reserve() until the time when an insertion would make the size of the vector greater than the size specified in the most recent call to reserve().

所以是的,你可以确定。

编辑: 正如@Bo Persson 提到的,有一个问题。如果我们从不调用 reserve() ,标准不会说什么。然而在实践中它运作良好,因为没有实现会关心你是否调用了reserve。我相信这是错误。正如@Martin 在他在 C++0x 草稿中的回答中提到的那样,它已得到纠正。

关于c++ - std::vector 何时重新分配其内存数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5410035/

相关文章:

c# - 将数组从 c++ 传递到 c#,然后按值或按引用返回,哪个更好,为什么?

c++ - 为什么这个联盟显然持有不止一个值(value)?

c++ - 标准库/模板容器的 const 语义的经验法则?

c++ - STL map 实例化

c++ - 对具有私有(private)变量的类 vector 使用排序

c++ - 我怎样才能为唯一的类组合获得一致的、唯一的标识符?

c++ - 通过调用 transform 方法对齐持有不同类型的两个容器

c++ - 从后面访问 vector

r - 在R中,如何制作一个向量Y,其分量来自正态分布?

c++ - 改变数组