C++ 在 std::vector 中搜索

标签 c++ stl vector find

假设我有这样一个 vector :

vector< pair<string, pair<int, int> > > cont;

现在我想在 cont 中找到 first 等于 "ABC" 的元素。我如何使用 STL 为我们提供的仿函数和算法(find_if、is_equal??)轻松地做到这一点。 (请不要使用 Boost,也不要使用新的 C++。)

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

最佳答案

有点像

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

或 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";
});

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

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

关于C++ 在 std::vector 中搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14019181/

相关文章:

c++ - 编译时出现信号/槽错误

c++ - 两个其他方面相同的功能(一个使用模板模式,另一个不使用)

c++ - 这个模板函数的最后一个参数有什么用?

c++ - 如何使用 begin() 自由函数

c++ - std::set 中的函数和方法指针

c++ - 在 gcc 中使用 O2 时如何将此 vector 优化快 10 倍?

C++ Array vs Vector 性能测试解释

c++ - 向 Q_Object 构造函数添加参数

c++ - 修复 std::vector<std::vector<UC>> lum 中调用 'assign' 时出现的错误:没有匹配函数;

C++ 无法将数据输入私有(private) vector (无效使用)