检索 STL 映射键

发布于 2024-10-02 08:09:59 字数 76 浏览 0 评论 0原文

有没有办法(除了将键存储为值的一部分并迭代映射之外)从 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

瘫痪情歌 2024-10-09 08:09:59
for (std::map<key, value>::iterator iter = m.begin(); iter != m.end(); ++iter)
    iter->first; // this is the key
for (std::map<key, value>::iterator iter = m.begin(); iter != m.end(); ++iter)
    iter->first; // this is the key
听,心雨的声音 2024-10-09 08:09:59

您可以使用 for 循环。

for (const auto & keyVal : myMap)
    keyVal.first;

You can use a for loop.

for (const auto & keyVal : myMap)
    keyVal.first;
我是男神闪亮亮 2024-10-09 08:09:59

如果您经常需要获取这些密钥(例如在大循环中),那么您可能有兴趣使用 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文