有人可以解释为什么我没有得到相同的输出吗?
main.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/