Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find_if and std::pair, but just one element

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?

like image 424
PersianGulf Avatar asked Aug 17 '12 14:08

PersianGulf


1 Answers

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));
like image 169
juanchopanza Avatar answered Sep 30 '22 07:09

juanchopanza