Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

map auto-based loop single element access C++

I'm trying to understand the "theory" besides the auto loop over

std::map

elements in C++. I have a std::map with a std::string as KEY and a vector<std:string> as VALUE. I can access its elements with:

for ( auto &element : myMap ) {
    std::cout << element.first << ": " << '\t';
    for ( std::string subElement : element.second ) std::cout << subElement << ", ";
  }
}

as for the loop over the vector<string> elements I know that I could put "auto" instead of "std::string". But what would be the equivalent for the map in such case? I studied and searched around and I found in that post that each map element is accessed as a

map< K, V>::value_type

but how would I write it down? I tried:

for ( std::map<std::string, vector<std::string>> &pz : myMap ) {
    // print ...
}

and similars, but they just does not work.

like image 606
cccnrc Avatar asked Jun 17 '19 03:06

cccnrc


1 Answers

std::map::value_type is defined as the type of std::map's element, which is std::pair<const Key, T> (i.e. std::pair<const std::string, vector<std::string>> here). You should use it as

for ( std::map<std::string, vector<std::string>>::value_type &pz : myMap ) {
    //                                          ^^^^^^^^^^^^
    // print ...
}
like image 136
songyuanyao Avatar answered Oct 28 '22 23:10

songyuanyao