How do you iterate over the keys of a std::map?

I am looking for a way to iterate through the keys of a map in C++ 17. The way that I have in mind right now is based on the answer of this question, the way is presented below.

for (auto const& [i, val] : myMap)
...

However, I do not need to use the value val, I just need the value i. Therefore, the piece of code ... does not contain any call to the value val. Consequently, whenever I compile the code, the following warning message appears:

warning: unused variable ‘val’ [-Wunused-variable]
         for (auto const& [i, val] : myMap){
                                  ^

What I want is to find a way to iterate through (only) the keys of the map, ignoring the values. Does anyone have any idea how to do it?

Upvotes: 11

Views: 21763

Answers (6)

Owl66
Owl66

Reputation: 185

for(auto const & pair : myMap) since map internally stored element in std::pair format, hence you can access the element by writing, pair.first; for key or pair.second; for value.

Upvotes: -1

einpoklum
einpoklum

Reputation: 131666

Two options:

  1. A ranged-for version of @πάνταῥεῖ 's answer:

    for (auto const& pair : myMap) {
        auto key = pair.first;
        // etc. etc.
    }
    
  2. Use the ranges-v3 library, or std::ranges in C++20, to adapt the range myMap.begin() and myMap.end() by projecting it onto its first coordinate. Then you'd write something like:

    for (auto key : std::views::keys(myMap)) {
        // etc. etc.
    }
    

    See also std::views::keys. You can do this without ranges by creating a new container which only contains the keys, but that could be expensive for a larger map.

    (If you have weird, heavy keys, then const auto& key instead of auto key.)

Upvotes: 12

user4640261
user4640261

Reputation:

How about using Go-like unused variable declaration with _:

for(auto const& [i, _] : myMap)
...

Upvotes: 0

Aykhan Hagverdili
Aykhan Hagverdili

Reputation: 29985

You can avoid the unused warnings by casting to void:

for (auto const& [key, val] : m) {
  (void)val;  // To avoid unused warnings

  // use key
}

Upvotes: 1

user12694894
user12694894

Reputation: 1

for (auto& [key, std::ignore] : m) {
  // use key
}

Upvotes: -4

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

Does anyone have any idea how to do it?

Sure! You can just use a traditional for loop with an iterator:

for(auto it = myMap.begin(); it != myMap.end(); ++it) {
    auto i = it->first;
    // ...
}

Upvotes: 3

Related Questions