user11508332
user11508332

Reputation: 667

How to check if a std::map contains a key that satisfies a predicate

In C++, say you have a std::map<int,int> - how would you use stl algorithms/libraries to find if there is a key that satisfies a certain predicate, e.g. finding if there is a key that is an odd number. So far I've got:

auto variable = std::find_if(my_map.begin(),my_map.end(), [](const auto& element) -> bool {return element%2 == 1;})
if (variable == my_map.end() .....

But how do I make sure the parameter in the predicate function is actually the key?

Upvotes: 4

Views: 1474

Answers (3)

lubgr
lubgr

Reputation: 38325

You can hide the pair-based iterator abstraction when using a range-based for loop with structured bindings. This is generally quite readable, although handling the not-found case adds some noise.

std::optional<int> result;

for (const auto& [key, value] : my_map)
   if (key % 2 == 1) {
       result = value; // or key
       break;
   }

if (result)
    /* ... */ ;

Using <algorithm> seems more idiomatic, though. On the other hand, linear traversal of a std::map is non-idiomatic anyhow.

Upvotes: 2

Eduardo Pascual Aseff
Eduardo Pascual Aseff

Reputation: 1166

Element is a pair, you can access its key with element.first. But to access variable, as an iterator you may use -> instead.

int main(){
  std::map<int,int> my_map;

  my_map[6] = 12;
  my_map[9] = 18;
  my_map[12] = 24;

  auto variable = std::find_if(my_map.begin(),my_map.end(), [](const auto& element) -> bool {return element.first%2 == 1;});
  if (variable != my_map.end()){
    std::cout << variable->first << " " << variable->second << "\n";
  }
}

Output: 9 18

Upvotes: 1

MyClass
MyClass

Reputation: 362

You can access the key via element.first like this

const auto variable = std::find_if(my_map.begin(), my_map.end(), [](const auto& element) {
      return element.first % 2 == 1; 
   }
);

if (variable != my_map.end()
{
   // found
}

Upvotes: 3

Related Questions