c++ std::find带有自定义比较器

C++ std::find with a custom comparator

本文关键字:自定义 比较器 find std c++      更新时间:2023-10-16

这就是我想要做的:

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不取。你试图传递valuecompare,这让我很困惑。不管怎样,看看文档。查看用法的区别:

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