std::map find_if condition style confusion

You can use a lambda function

int val = ...;
auto it = std::find_if(myMap.begin(), myMap.end(), 
   [val](const std::pair<int, ValueType> & t) -> bool { 
      return t.second.x == val;
   }
);

But as Kirill V. Lyadvinsky answer suggests the "first" element may not be what you expect.


Elements in the map are not sorted by value, they are sorted according to the key. So the phrase "the first element" has not much sense.

To find some element (not the first) that has x equal to some value you can write the functor as follows:

struct check_x
{
  check_x( int x ) : x_(x) {}
  bool operator()( const std::pair<int, ValueType>& v ) const 
  { 
    return v.second.x == x_; 
  }
private:
  int x_;
};

Then use it as follows:

// find any element where x equal to 10
std::find_if( myMap.begin(), myMap.end(), check_x(10) );

struct Pred
{
    Pred(int x) : x_(x) { }
    bool operator()(const std::pair<int, ValueType>& p)
    {
        return (x_ == p.second.x);
    }
private:
    int x_;
};

... = std::find_if(myMap.begin(), myMap.end(), Pred(NUMBER));

Tags:

C++

Stl