Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I print out C++ map values?

I have a map like this:

map<string, pair<string,string> > myMap; 

And I've inserted some data into my map using:

myMap.insert(make_pair(first_name, make_pair(middle_name, last_name))); 

How can I now print out all the data in my map?

like image 746
Zhi Rui Avatar asked Dec 28 '12 14:12

Zhi Rui


People also ask

How do you find the value of an element on a map?

Search by value in a Map in C++ Given a set of N pairs as a (key, value) pairs in a map and an integer K, the task is to find all the keys mapped to the give value K. If there is no key value mapped to K then print “-1”. Explanation: The 3 key value that is mapped to value 3 are 1, 2, 10.

How are values stored in map C++?

Maps are associative containers that store elements in a combination of key values and mapped values that follow a specific order. No two mapped values can have the same key values. In C++, maps store the key values in ascending order by default.


1 Answers

for(map<string, pair<string,string> >::const_iterator it = myMap.begin();     it != myMap.end(); ++it) {     std::cout << it->first << " " << it->second.first << " " << it->second.second << "\n"; } 

In C++11, you don't need to spell out map<string, pair<string,string> >::const_iterator. You can use auto

for(auto it = myMap.cbegin(); it != myMap.cend(); ++it) {     std::cout << it->first << " " << it->second.first << " " << it->second.second << "\n"; } 

Note the use of cbegin() and cend() functions.

Easier still, you can use the range-based for loop:

for(const auto& elem : myMap) {    std::cout << elem.first << " " << elem.second.first << " " << elem.second.second << "\n"; } 
like image 111
Armen Tsirunyan Avatar answered Sep 20 '22 16:09

Armen Tsirunyan