c – 矢量的容量在push_back()之后变化

前端之家收集整理的这篇文章主要介绍了c – 矢量的容量在push_back()之后变化前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有人可以解释为什么我不能得到相同的输出? @H_502_2@main.cpp中:

  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. struct Cell
  7. {
  8. vector<int> vtx;
  9. };
  10.  
  11. int main()
  12. {
  13. vector <Cell> cells;
  14. Cell tmp;
  15. tmp.vtx.reserve(5);
  16. cells.push_back (tmp);
  17. cout << tmp.vtx.capacity() << endl;
  18. cout << cells[0].vtx.capacity() << endl;
  19. return 0;
  20. }
@H_502_2@输出

  1. 5
  2. 0

解决方法

因为取向量A并将其复制到向量B不能保证向量B将具有与向量A相同的容量.通常,新向量将仅分配足够的存储器来保存被复制到其中的元素. @H_502_2@事实上,有一个老技巧,使用这个,称为减少能力的技巧:

  1. int main()
  2. {
  3. vector<int> v { 1,2,3,4,5 };
  4. v.clear(); // capacity still non-zero
  5.  
  6. vector<int>(v).swap(v); // capacity now zero (maybe)
  7. }
@H_502_2@…虽然在技术上,whether this actually works is entirely implementation-dependent.

@H_502_2@如果您将向量移入,而不是复制,那么没有重新分配,缓冲区实际上是相同的缓冲区,容量不会改变:

  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. struct Cell
  7. {
  8. vector<int> vtx;
  9. };
  10.  
  11. int main()
  12. {
  13. vector <Cell> cells;
  14. Cell tmp;
  15. tmp.vtx.reserve(5);
  16. cout << tmp.vtx.capacity() << endl;
  17. cells.push_back (std::move(tmp));
  18. cout << cells[0].vtx.capacity() << endl;
  19. return 0;
  20. }
  21.  
  22. // 5
  23. // 5
@H_502_2@(请注意,我不得不在移动前先移动第一个通话,否则我会加油处于未知状态.)

猜你在找的C&C++相关文章