有人可以解释为什么我不能得到相同的输出?
@H_502_2@main.cpp中:
@H_502_2@输出:
- #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
解决方法
因为取向量A并将其复制到向量B不能保证向量B将具有与向量A相同的容量.通常,新向量将仅分配足够的存储器来保存被复制到其中的元素.
@H_502_2@事实上,有一个老技巧,使用这个,称为减少能力的技巧:
@H_502_2@…虽然在技术上,whether this actually works is entirely implementation-dependent. @H_502_2@如果您将向量移入,而不是复制,那么没有重新分配,缓冲区实际上是相同的缓冲区,容量不会改变:
- 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)
- }
@H_502_2@(请注意,我不得不在移动前先移动第一个通话,否则我会加油处于未知状态.)
- #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