find_if and std::pair, but just one element

依然范特西╮ 提交于 2019-11-27 02:55:15

问题


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?


回答1:


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));



回答2:


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.




回答3:


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;
    }


来源:https://stackoverflow.com/questions/12008059/find-if-and-stdpair-but-just-one-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!