find_if和std :: pair,但只是一个元素

问题描述 投票:6回答:3

假设我有以下代码:

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 */

现在我需要在其中搜索一个int元素,所以:

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

我该怎么做?

c++ vector lambda iterator std-pair
3个回答
14
投票

写一个带有std::pair的一元谓词,如果first元素等于给定值,则返回true。

例如:

struct CompareFirst
{
  CompareFirst(int val) : val_(val) {}
  bool operator()(const std::pair<int,char>& elem) const {
    return val_ == elem.first;
  }
  private:
    int val_;
};

然后

// find first element with first == 42
vectorIt = std::find_if(myVec.begin(),myVect.end(), CompareFirst(42));

13
投票

这使用C ++ 11 lambda表达式,并给出你想要找到的value

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

其中containermyVecmyList

lambda表达式[&value](...){...}是临时表达式的功能等价(很像你可以将“3 + 2”作为参数传递给int参数。它将被转换为一个函数对象(很像juanchopanza的答案)编译器。它使您免于键入并保持代码本地化。


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

为了找到所需的int值,您应该使用以下内容:

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

例如 :

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;
    }
© www.soinside.com 2019 - 2024. All rights reserved.