【问题标题】:How I can get a pointer to the key in an unordered_map when I am iterating over it?迭代 unordered_map 时如何获取指向键的指针?
【发布时间】:2020-07-27 16:24:44
【问题描述】:

来自 C 思维我对 c++ 标准库的经验很少,我想知道是否有人知道我在迭代 unordered_map 时如何获得指向键的指针? 更具体地说,我正在尝试做这样的事情:

std::unordered_map<std::string, int> my_map;
std::string *the_string_i_care_about;
for(auto& itr : my_map) {
    if (itr.first == "pick me!" ) {
        the_string_i_care_about = &itr.first;
    }
}
...
do stuff with the_string_i_care_about later

如果重要的话,在我的真实代码中,我没有一对字符串和整数,而是两个 POD 结构(我将单位映射到战略游戏中的坐标)。

【问题讨论】:

  • 您显示的代码有什么问题?请提供任何错误消息或您得到的错误结果。
  • &amp;itr.first???

标签: c++ iterator unordered-map


【解决方案1】:

std::unordered_map存储key为const,其元素类型为std::pair&lt;const Key, T&gt;the_string_i_care_about 也应该是指向 const 的指针。例如

std::unordered_map<std::string, int> my_map;
const std::string *the_string_i_care_about;
for(auto& itr : my_map) {
    if (itr.first == "pick me!" ) {
        the_string_i_care_about = &itr.first;
    }
}

【讨论】:

  • 但如果它是 const 它不能改变,代码的重点是每次迭代时我可能会得到一个不同的键。当然,在我的示例中,我总是会得到“pick me”的字符串,但假设我正在检查更动态的东西,比如键是我点击的坐标?
  • @SebastianJensen 指针不是const,它可以在运行时指向不同的字符串。但是,如果您想指向 map 中的键,那么它必须是指向 const 字符串的指针。您仍然可以在运行时将其指向不同的 const 字符串。
  • @SebastianJensen 您可能使用了错误的容器;您不能也不应该直接修改存储在std::unordered_map 中的密钥。
猜你喜欢
  • 1970-01-01
  • 2019-08-24
  • 2018-09-04
  • 1970-01-01
  • 2012-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多