Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of List inside map C++

Tags:

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.

like image 508
user987316 Avatar asked Nov 19 '11 07:11

user987316


People also ask

What is the difference between list and map in C++?

Lists:: A list is an ordered collection of elements that are distinguished by their indices. List elements can be of any data type—primitive types, collections, sObjects, user-defined types, and built-in Apex types. A map is a collection of key-value pairs where each unique key maps to a single value.

How to add elements to map?

The standard solution to insert new elements into a map is using the std::map::insert function. It inserts the specified key-value pair into the map only if the key already doesn't exist. If the key already exists in the map, the element is not inserted.

How to add values to map in Cpp?

map::insert() function is an inbuilt function in C++ STL, which is defined in header file. insert() is used to insert new values to the map container and increases the size of container by the number of elements inserted.

What is map in C?

What is a map in C++? A C++ map is a way to store a key-value pair. A map can be declared as follows: #include <iostream> #include <map> map<int, int> sample_map; Each map entry consists of a pair: a key and a value.


1 Answers

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}};
like image 124
bames53 Avatar answered Oct 04 '22 07:10

bames53