簡體   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