我怎么能初始化unordered_map&lt; vector <int>&gt;?</int>

时间:2014-07-24 08:49:26

标签: c++ vector constructor stl unordered-map

我在工作中遇到了一个问题

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

那么我怎样才能初始化嵌套容器,这样当我将一个键插入哈希表时 并且值(向量)将为十零?

4 个答案:

答案 0 :(得分:3)

您可以使用列表初始化:

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) }
  };

答案 1 :(得分:2)

这很简单:

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,数据为包含十个条目的向量。

答案 2 :(得分:2)

不允许用户直接访问地图,让他们通过访问者,这样你就可以确保向量的填充方式如下:

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;
}

答案 3 :(得分:1)

根据你在评论中所说的,你需要一个固定大小的数组。 这是一个小例子:

#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

不是我最喜欢的选择,但你可以这样做。

相关问题