Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::map find_if condition style confusion

Tags:

c++

stl

I'd like to use std::find_if to search for the first element in my map that has a certain value in a specific element of its value structure. I'm a little confused though. I think I need to use bind1st or bind2nd, but I'm not positive that's the right way to go.

Here's some pseudo-code:

struct ValueType { int x, int y, int z };

std::map<int, ValueType> myMap;

... {populate map}

std::map<int, ValueType>::iterator pos = std::find_if(myMap.begin(), myMap.end(), <?>); 

So, let's say that I wanted to find the first element of the map where the .x member of the ValueType was equal to a certain integer value (which can change each call).

What would be the best way to write a function or function object to achieve this? I understand that the <?> has to be a unary predicate which makes me think I'll need bind1st or bind2nd to provide the integer value I'm checking for, but I'm not sure how to go about it. It's been way too long since I looked at this stuff! >.<

like image 592
John Humphreys Avatar asked Nov 08 '11 16:11

John Humphreys


2 Answers

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.

like image 164
Tyler Hyndman Avatar answered Oct 13 '22 10:10

Tyler Hyndman


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) );
like image 22
Kirill V. Lyadvinsky Avatar answered Oct 13 '22 09:10

Kirill V. Lyadvinsky