Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 928
user11508332 Avatar asked Oct 21 '25 14:10

user11508332


1 Answers

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
}
like image 51
MyClass Avatar answered Oct 23 '25 03:10

MyClass



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!