繁体   English   中英

我如何初始化unordered_map &lt;向量 <int> &gt;?

[英]how could I initialize unordered_map< vector<int> >?

我在工作中遇到一个问题

我的c ++类中的vector<int>上有一个unordered_map
像这样unordered_map < int, vector<int> >

所以我怎么初始化嵌套的容器,以便当我在哈希表中插入一个键并且value(vector)为十零时?

您可以使用列表初始化:

std::unordered_map<int, std::vector<int>> m
  { { 2, std::vector<int>(10, 0) }
  , { 5, std::vector<int>(10, 0) }
  , { 6, std::vector<int>(10, 0) }
  , { 9, std::vector<int>(10, 0) }
  };

很简单:

std::unordered_map<int, std::vector<int>> my_map;

my_map[123] = std::vector<int>{1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };

现在, my_map将包含一个条目,键123和数据是包含十个条目的向量。

不允许用户直接访问地图,让他们通过访问器,以便您可以确保按所需方式填充矢量:

class FooBar
{
public:
  // access the map
  std::vector<int>& operator[](int n);

private:
  std::unordered_map<int, std::vector<int>> map;
};

std::vector<int>& FooBar::operator[](int n)
{
  auto iter = map.find(n);
  if (iter == map.end()) // index not found, so insert it
    iter = map.emplace(n, std::vector<int>(10, 0)).first;
  return *iter;
}

根据您在注释中所说的,您需要一个固定大小的数组。 这里有个小例子:

#include <array>
#include <unordered_map>
#include <iostream>

int main(int, char const *[])
{
    std::unordered_map<int, std::array<int, 10>> the_map;

    std::cout << the_map[0][1] << std::endl;
    the_map[0][2]++;
    std::cout << the_map[0][2] << std::endl;
    return 0;
}

输出将是:

0
1

如果要更改默认值,可以执行以下操作:

struct my_array : public std::array<int, 10> { my_array() { fill(2); }  };

int main(int , char const *[])
{
    std::unordered_map<int, my_array> the_map;

    std::cout << the_map[0][1] << std::endl;
    the_map[0][2]++;
    std::cout << the_map[0][2] << std::endl;
    return 0;
}

输出:

2
3

不是我最喜欢的选择,但是您可以通过这种方式进行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM