find_if and std::pair, but just one element
This uses C++11 lambda expressions, and 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 either myVec
or myList
.
The lambda expression [&value](...){...}
is the functional equivalence of a temporary expression (much like you can pass "3+2" as an argument to an int
parameter. It will be translated to a function object (much like the one in juanchopanza's answer) by the compiler. It saves you from typing and keeps your code localized.
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));
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 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()) {
cout << "not found\n";
}
else {
cout<< "found - first instance is < " << it->first <<"," << it->second << " >";
}
return 0;
}