简体   繁体   English

检索STL映射键

[英]retrieving STL map keys

有没有办法(除了存储密钥作为值的一部分并迭代地图)从STL地图中检索密钥,multimap(hash_map)a la Perl密钥(%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循环。

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 . 如果你经常需要获得这些键(比如在一个大循环中),那么你可能会对使用boost :: bimap感兴趣。 Otherwise you can use Nikola's solution that is correct. 否则,您可以使用正确的Nikola解决方案。

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. 它需要确保同步两个容器,但如果它足够孤立(在一个类中),那么它很容易设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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