c++ std::find带有自定义比较器
C++ std::find with a custom comparator
这就是我想要做的:
bool special_compare(const string& s1, const string& s2)
{
// match with wild card
}
std::vector<string> strings;
strings.push_back("Hello");
strings.push_back("World");
// I want this to find "Hello"
find(strings.begin(), strings.end(), "hell*", special_compare);
// And I want this to find "World"
find(strings.begin(), strings.end(), "**rld", special_compare);
但不幸的是,std::find
不是这样工作的。所以只使用STL,我怎么能做这样的事情呢?
根据您的评论,您可能正在寻找这个:
struct special_compare : public std::unary_function<std::string, bool>
{
explicit special_compare(const std::string &baseline) : baseline(baseline) {}
bool operator() (const std::string &arg)
{ return somehow_compare(arg, baseline); }
std::string baseline;
}
std::find_if(strings.begin(), strings.end(), special_compare("hell*"));
您需要使用的函数是:std::find_if
,因为std::find
不采用比较函数。
但std::find_if
不取值。你试图传递value和compare,这让我很困惑。不管怎样,看看文档。查看用法的区别:
auto it1 = std::find(strings.begin(), strings.end(), "hell*");
auto it2 = std::find_if(strings.begin(), strings.end(), special_compare);
希望对你有帮助。
您需要std::find_if()
,除非使用c++ 11编译器,否则使用起来很尴尬。因为这样,您就不需要硬编码要在某个比较器函数或实现函函数对象中搜索的值,而是可以在lambda表达式中完成:
vector<string> strings;
strings.push_back("Hello");
strings.push_back("World");
find_if(strings.begin(), strings.end(), [](const string& s) {
return matches_wildcard(s, "hell*");
});
然后在某处写一个matches_wildcard()
使用c++ 11 lambdas:
auto found = find_if(strings.begin(), strings.end(), [] (const std::string& s) {
return /* you can use "hell*" here! */;
});
如果你不能使用c++ 11的lambdas,你可以自己创建一个函数对象。创建类型和重载操作符
既然还没有人提到std::bind
,我就推荐这个
#include <functional>
bool special_compare(const std::string& s, const std::string& pattern)
{
// match with wild card
}
std::vector<std::string> strings;
auto i = find_if(strings.begin(), strings.end(), std::bind(special_compare, std::placeholders::_1, "hell*"));
我想有一个具有自定义查找逻辑的自定义类的示例,但没有找到任何这样的答案。所以我写了这个答案,它使用自定义比较器函数(c++ 11)来查找对象。
class Student {
private:
long long m_id;
// private fields
public:
long long getId() { return m_id; };
};
现在假设,我想找到m_id
与给定id匹配的student
对象。我可以这样写std::find_if
:
// studentList is a vector array
long long x_id = 3; // local variable
auto itr = std::find_if(studentList.begin(), studentList.end(),
[x_id](Student& std_val)
{ return std_val.getId() == x_id; }
);
if(itr == studentList.end())
printf("nothing found");
相关文章:
- std::设置自定义比较器
- 带自定义比较器的最小优先级队列
- 优先级队列自定义比较器
- 什么是自定义比较器以及如何在 C++ 的排序函数中使用它?
- 没有默认构造函数作为模板参数的自定义比较器
- 使用迭代器的自定义比较器函数
- Cython中带有自定义比较器的优先级队列
- gtest 期望无序元素与自定义比较器/匹配器一起使用
- 为什么在类或结构中传递自定义比较器函数?
- 在priority_queue中使用默认容器但自定义比较器
- 是否有任何统一的方法可以在 c++ 中创建自定义比较器?
- C++ priority_queue与自定义比较器并删除任何项目
- 如何在 C++11 中将 std::max 与自定义比较器一起使用?
- 通过函数指针对类内的 STL SET 使用自定义比较器
- 基于对象的两个属性的自定义比较器会引发异常
- 如何使用自定义比较器初始化类数据成员,该成员是 std::set
- 标准::set_intersection 带自定义比较器
- 使用自定义比较器C++映射,不插入所有元素
- 优先队列的自定义比较器
- C++ STL . 自定义比较器如何工作?