Shi*_*bli 9 c++ stdvector c++11
有人可以解释为什么我没有得到相同的输出?
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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
5
0
Run Code Online (Sandbox Code Playgroud)
Lig*_*ica 16
因为采用矢量A
并将其复制到矢量B
并不能保证矢量B
具有与矢量相同的容量A
.通常,新向量将仅分配足够的内存来保存要复制到其中的元素.
事实上,有一个老技巧,利用这个,称为减少容量技巧:
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)
}
Run Code Online (Sandbox Code Playgroud)
......但从技术上讲,这实际上是否有效依赖于实现.
如果你移动向量而不是复制它,那么就没有重新分配,缓冲区实际上是相同的缓冲区,容量不会改变:
#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
Run Code Online (Sandbox Code Playgroud)
(请注意,我必须在移动cout
之前移动第一个调用,否则我将cout
处于未知状态.)