# [ACCEPTED]-find_if and std::pair, but just one element-std-pair

Score: 15

Write a unary predicate that takes an `std::pair`, and 2 returns true if the `first` element is equal to 1 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));
``````
Score: 14

This uses C++11 lambda expressions, and 9 given a `value` that you want to find:

``````std::find_if(container.begin(), container.end(),
[&value](std::pair<int, char> const& elem) {
return elem.first == value;
});
``````

where `container` is 8 either `myVec` or `myList`.

The lambda expression `[&value](...){...}` is the 7 functional equivalence of a temporary expression 6 (much like you can pass "3+2" as an argument 5 to an `int` parameter. It will be translated 4 to a function object (much like the one 3 in juanchopanza's answer) by the compiler. It 2 saves you from typing and keeps your code 1 localized.

Score: 2
``````template <class T,class S> struct pair_equal_to : binary_function <T,pair<T,S>,bool> {
bool operator() (const T& y, const pair<T,S>& x) const
{
return x.first==y;
}
};
``````

In order to find needed int value you should 1 use following :

``````int find_me = 1;//chenge the value as you want
vector< pair <int, char> >::iterator it =
find_if(myVec.begin(),myVec.end(),bind1st(pair_equal_to<int,char>(),find_me));
``````

For example :

``````int main() {
vector< pair <int, char> > myVec;
pair<int,char> p1 = make_pair(1,'a');
pair<int,char> p2 = make_pair(2,'b');
pair<int,char> p3 = make_pair(1,'c');
myVec.push_back(p1);
myVec.push_back(p2);
myVec.push_back(p3);
vector< pair <int, char> >::iterator it = find_if(myVec.begin(),myVec.end(),bind1st(pair_equal_to<int,char>(),1));
if (it == myVec.end()) {