find_if and std::pair, but just one element

PersianGulf picture PersianGulf · Aug 17, 2012 · Viewed 11k times · Source

Suppose i have the following code:

std::vector< std::pair <int, char> > myVec; 
or 
std::list< std::pair <int, char> > myList; 
/* then ***************/
std::list< std::pair <int, char> >::iterator listIt; 
or 
std::vector< std::pair <int, char> >::iterator vectorIt;

/* No difference between vector and list */

Now i need to search just for one int element in them, So:

vectorIt = std::find_if(myVec.begin(),myVect.end(),make_pair(.....));
                                                   ^^^^^^^^^^^^^^^^^

how can i do it?

Answer

juanchopanza picture juanchopanza · Aug 17, 2012

Write a unary predicate that takes an std::pair, and returns true if the first element is equal to a given value.

For example:

struct CompareFirst
{
  CompareFirst(int val) : val_(val) {}
  bool operator()(const std::pair<int,char>& elem) const {
    return val_ == elem.first;
  }
  private:
    int val_;
};

Then

// find first element with first == 42
vectorIt = std::find_if(myVec.begin(),myVect.end(), CompareFirst(42));