user987316
user987316

Reputation: 942

Use of List inside map C++

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.

Upvotes: 15

Views: 37950

Answers (1)

bames53
bames53

Reputation: 88215

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

Upvotes: 38

Related Questions