C++在std :: vector中搜索

Nar*_*rek 5 c++ stl vector find

说我有这样的矢量:

vector< pair<string, pair<int, int> > > cont;
Run Code Online (Sandbox Code Playgroud)

现在我想在cont找到与它first相等的元素"ABC".如何使用STL为我们提供的仿函数和算法轻松完成此任务(find_if,is_equal ??).(请不要提升,也不要使用新的C++.)

编辑:是否可以不定义谓词仿函数?

For*_*veR 7

就像是

typedef std::pair<std::string, std::pair<int, int> > pair_t;

struct Predicate : public std::unary_function<pair_t, bool>
{
public:
   Predicate(const std::string& s):value(s) { }
   result_type operator () (const argument_type& pair)
   {
      return pair.first == value;
   }
private:
   std::string value;
};

std::vector<pair_t>::const_iterator pos = std::find_if(cont.begin(), cont.end(),
Predicate("ABC"));
Run Code Online (Sandbox Code Playgroud)

或lambda,如果是C++ 11.

auto pos = std::find_if(cont.begin(), cont.end(),
[](const std::pair<std::string, std::pair<int, int>>& pair)
{
    return pair.first == "ABC";
});
Run Code Online (Sandbox Code Playgroud)

真的,没有结构,有一种不太好的方法可以做这样的事情.

typedef std::pair<std::string, std::pair<int, int> > pair_t;

namespace std {
template<>
bool operator ==<> (const pair_t& first, const pair_t& second)
{
   return first.first == second.first;
}
}

std::vector<pair_t>::const_iterator pos = std::find_if(cont.begin(), cont.end(),
std::bind2nd(std::equal_to<pair_t>(), std::make_pair("ABC", std::make_pair(1, 2))));
Run Code Online (Sandbox Code Playgroud)