假设我有这样一个 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/