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?
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.
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.
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"; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With