【问题标题】:find_if and std::pair, but just one elementfind_if 和 std::pair,但只有一个元素
【发布时间】:2012-08-14 00:51:49
【问题描述】:

假设我有以下代码:

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


【解决方案1】:

编写一个接受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));

【讨论】:

    【解决方案2】:

    这使用了 C++11 的 lambda 表达式,并给出了您想要查找的 value

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

    其中containermyVecmyList

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

    【讨论】:

    【解决方案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;
      }
    };
    

    为了找到所需的 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;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-04
      • 2018-05-17
      • 2015-03-09
      • 1970-01-01
      • 2011-04-18
      • 1970-01-01
      相关资源
      最近更新 更多