加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 05:49:51 所属栏目:百科 来源:网络整理
导读:有人可以解释为什么我不能得到相同的输出? main.cpp中: #include iostream#include vectorusing namespace std;struct Cell{ vectorint vtx;};int main(){ vector Cell cells; Cell tmp; tmp.vtx.reserve(5); cells.push_back (tmp); cout tmp.vtx.capacit
有人可以解释为什么我不能得到相同的输出?

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

解决方法

因为取向量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)
}

…虽然在技术上,whether this actually works is entirely implementation-dependent.

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

#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

(请注意,我不得不在移动前先移动第一个通话,否则我会加油处于未知状态.)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读