【问题标题】:capacity of vector is 0 when i am inserting it into an un-ordered map当我将向量插入无序地图时,向量的容量为 0
【发布时间】:2020-01-14 06:00:51
【问题描述】:

我保留了一个大小为 40 的向量,但是当我将它作为一对插入到无序映射中时,向量容量变为 0。为什么会这样?

#include<vector> 
#include <iostream>
#include <unordered_map>
using namespace std;

int main() {
   std::vector<int> a;
   a.reserve(40);
   std::cout<<a.capacity()<<std::endl;

   std::unordered_map<int,vector<int>> _map;
   _map.insert(std::make_pair(1,a));
   std::cout<<_map[1].capacity()<<std::endl;



    return 0;
}

【问题讨论】:

标签: c++ c++11 vector unordered-map


【解决方案1】:

make_pair 将复制构造 (6) 一个新向量 which does not retain the capacity

您也可以通过使用std::move 强制移动构造函数(7)does retain capacity,但这会过于复杂。

_map.insert(std::make_pair(1, std::move(a)));

我建议您在构造向量时简单地保留大小,而不是保留容量。

std::vector<int> a(40);

【讨论】:

    【解决方案2】:

    构造std::vector 的副本不需要保留构造它的对象的容量。只需要保存内容即可。

    来自https://en.cppreference.com/w/cpp/container/vector/vector

    复制构造函数。用 other 的内容的副本构造容器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多