c++ - push_back() 之后 vector 的容量发生变化

标签 c++ c++11 stdvector

有人可以解释为什么我没有得到相同的输出吗?

ma​​in.cpp:

#include <iostream>
#include <vector>

using namespace std;

struct Cell
{
    vector<int> vtx;
};

int main()
{
    vector <Cell> cells;
    Cell tmp;
    tmp.vtx.reserve(5);
    cells.push_back (tmp);
    cout << tmp.vtx.capacity() << endl;
    cout << cells[0].vtx.capacity() << endl;
    return 0;
}

输出:

5
0

最佳答案

因为获取 vector A 并将其复制到 vector B 并不能保证 vector B 与 vector 具有相同的容量>一个。通常,新 vector 只会分配足够的内存来容纳要复制到其中的元素。

事实上,有一个古老的技巧可以利用它,称为减少容量技巧:

int main()
{
   vector<int> v { 1,2,3,4,5 };
   v.clear();                   // capacity still non-zero

   vector<int>(v).swap(v);      // capacity now zero (maybe)
}

…不过,从技术上讲,whether this actually works is entirely implementation-dependent .

如果你移动 vector ,而不是复制它,那么就没有重新分配,缓冲区实际上是同一个缓冲区,容量不会改变:

#include <iostream>
#include <vector>

using namespace std;

struct Cell
{
    vector<int> vtx;
};

int main()
{
    vector <Cell> cells;
    Cell tmp;
    tmp.vtx.reserve(5);
    cout << tmp.vtx.capacity() << endl;
    cells.push_back (std::move(tmp));
    cout << cells[0].vtx.capacity() << endl;
    return 0;
}

// 5
// 5

(请注意,我必须在移动之前将第一个 cout 调用移动到.)

关于c++ - push_back() 之后 vector 的容量发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24660533/

相关文章:

c++ - 删除 std::vector<std::string> 中与另一个给定 std::string 中的字符匹配的元素

c++ - 链接器 - 模块机器类型冲突

C++ 没有合适的默认构造函数可用 - 继承的模板化构造函数没有参数

c++ - 将参数包传递给 emplace STL 函数会导致编译错误

c++ - xvalue 和 prvalue 之间的一些区别

C++ - 使用 std::vector 和相关内存管理的正确方法

c++ - Qt Creator 在指定的调试文件夹中创建调试和发布文件夹

c++ - calloc 创建的数组未按预期运行

c++ - 多线程boost asio中的随机EOF

c++ - std::vector 和内存分配