Use of List inside map C++

2020-07-06 01:39发布

Can I use following syntax:

 std::map<int,std::list<int>> mAllData;

Where Key Value(int) will be ID of data, and said data could have multiple types so storing all them against said key value. I am trying to use it.

标签: c++
1条回答
倾城 Initia
2楼-- · 2020-07-06 02:22
std::map<int,std::list<int>> my_map;
my_map[10].push_back(10000);
my_map[10].push_back(20000);
my_map[10].push_back(40000);

Your compiler may not support the two closing angle brackets being right next to each other yet, so you might need std::map<int,std::list<int> > my_map.

With C++11 my_map can be initialized more efficiently:

std::map<int,std::list<int>> my_map {{10, {10000,20000,40000}}};

Also, if you just want a way to store multiple values per key, you can use std::multimap.

std::multimap<int,int> my_map;
my_map.insert(std::make_pair(10,10000));
my_map.insert(std::make_pair(10,20000));

And in C++11 this can be written:

std::multimap<int,int> my_map {{10,10000},{10,20000}};
查看更多
登录 后发表回答