简体   繁体   中英

how could I initialize unordered_map< vector<int> >?

I met a question in my work

There is an unordered_map on vector<int> in my c++ class
like this unordered_map < int, vector<int> >

so how could I initialize the nested container so that when I insert a key to the hash table and the value(vector) will be ten zero ?

You can use list initialization:

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

It's very simple:

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

Now my_map will contain one entry, with the key 123 and data being a vector containing ten entries.

Do not allow users to access the map directly, make them go through an accessor so you can ensure the vector gets populated how you want:

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

According to what you stated in the comments you need a fixed size array. Here a small example:

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

Output will be:

0
1

If you want to change the default value you can do something like:

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

Output:

2
3

Not my favorite choice, but you can do it this way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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