retrieving STL map keys
Is there a way (besides storing the key as part of the value and iterating through the map) of retrieving the keys from an STL map, multimap (hash_map开发者_运维知识库) a la Perl keys(%hash)?
for (std::map<key, value>::iterator iter = m.begin(); iter != m.end(); ++iter)
iter->first; // this is the key
You can use a for loop.
for (const auto & keyVal : myMap)
keyVal.first;
If you often need to get those keys (like in a big loop) then you might be interested in using boost::bimap. Otherwise you can use Nikola's solution that is correct.
Sometimes I put keys copies in another container when adding elements to a map. It require to be sure to synchronize the two containers but if it's isolated enough (in a class) then it's easy to setup.
精彩评论