简体   繁体   中英

Issue with output for nested std::map

std::map<int, std::map<std::string, std::pair<int, std::string>>>mfvs;

I want to output the std::string the first part of inner map.

for (const auto& iter :mfvs)
{
std::cout << iter.second.first << "\n";
}

this gives me an error

iter.second is an std::map , and as such it doesn't have first .

If you want to print the first (with lowest key) element (and you are sure it exists), then do this:

std::cout << iter.second.begin()->first << "\n";

.begin() will return you the first element of the map , and ->first will get its key. If you want to print the value of it as well, something along the lines of the following code will work

auto firstElem = iter.second.begin();
std::cout << firstElem->first << ": " << firstElem->second.first << ", " << firstElem->second.second << "\n";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM