开发者

retrieving STL map keys

开发者 https://www.devze.com 2023-01-24 15:45 出处:网络
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:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消