Search code examples
c++iteratorunordered-map

How I can get a pointer to the key in an unordered_map when I am iterating over it?


coming from a C mindset I have very little experience with the c++ standard library and I wonder if anyone knows how I can get a pointer to the key in an unordered_map when I am iterating over it? To be more specific, I am trying to do something like this:

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

If it matters, in my real code I do not have a pair of string and int, but of two POD structs (I am mapping units to coordinates in a strategy game).


Solution

  • std::unordered_map stores key as const, its element's type is std::pair<const Key, T>; the_string_i_care_about should be pointer to const too. e.g.

    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;
        }
    }