检索 STL 映射键
有没有办法(除了将键存储为值的一部分并迭代映射之外)从 STL 映射、多重映射(hash_map)和 Perl 键(%hash)中检索键?
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)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 for 循环。
You can use a for loop.
如果您经常需要获取这些密钥(例如在大循环中),那么您可能有兴趣使用 boost::bimap。否则你可以使用尼古拉的正确解决方案。
有时,当我向地图添加元素时,我会将密钥副本放入另一个容器中。它需要确保同步两个容器,但如果它足够隔离(在一个类中),那么它很容易设置。
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.