Find_if and std :: pair, but only 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 for only one int element in them: So:

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

How can i do this?

+6
source share
3 answers

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

For instance:

 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)); 
+13
source

It uses C ++ 11 lambda expressions and sets the value 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 the temporary expression (just as you can pass "3 + 2" as an argument to an int parameter. It will be translated to a function object (like one from juanchopanza's answers) by the compiler, this saves you from typing and saving your code.

+11
source
 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; } }; 

To find the right int value, you should use the 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 instance:

 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; } 
+2
source

Source: https://habr.com/ru/post/923131/


All Articles