c++ - std::lower_bound 的比较函数

标签 c++ stl comparison binary-search

我有一个 PersonsDB 类,其成员变量 __emails它应该是指向 Person 类对象的指针的排序 vector (按 Person 电子邮件排序)。我的计划是使用 lower_bound 和自定义比较函数来获取插入下一个指针的迭代器。 成员(member)功能email()仅返回一个字符串。

bool PersonsDB::compare_email(Person * person_1, Person * person_2) const {
    return ((*person_1).email() < (*person_2).email());
}

vector<Person *>::iterator PersonsDB::email_exists(const string & email) {

    Person * dummy_person = new Person("", "", email, 0);

    auto i = lower_bound(__emails.begin(), __emails.end(), dummy_person, compare_email);

    if (i != __emails.end() && !((*dummy_person).email() < (*i)->email()))
        return i; // found
    else
        return __emails.end(); // not found

}

我试图遵循这个answer这建议创建一个虚拟对象。但是,我的代码无法编译并出现以下错误:

   main.cpp:121:87: error: invalid use of non-static member function ‘bool PersonsDB::compare_email(Person*, Person*) const’
         auto i = lower_bound(__emails.begin(), __emails.end(), dummy_person, compare_email);
                                                                                           ^

非常感谢任何帮助,谢谢!

最佳答案

即使您没有专门询问这一点,但是...没有必要创建一个 dummy_person (更不用说在堆上!):lower_bound 可以使用异构比较仿函数:

std::vector<Person *>::iterator
PersonsDB::email_exists(const std::string & email) {
    auto it = std::lower_bound(
        __emails.begin(), __emails.end(), email,
        [](Person * p, const std::string & s) { return p->email() < s; });

    return (it != __emails.end() && it->email() == email)
           ? it
           : __emails.end();
}

比较仿函数最容易表达为 lambda,不需要命名函数。

关于c++ - std::lower_bound 的比较函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49440588/

相关文章:

c++ - 没有导出的 LD_LIBRARY_PATH

c++ - 编译多个文件时出现奇怪的 undefined reference 错误

c++ - 调试后 CMD 窗口什么也没有显示

c++ - 管理指针 vector 和对象 vector 的模板类

c - 小于(<)float与c中if语句的比较

c++ - 为什么在比较中将常量放在变量之前?

Javascript 空字符串比较

c++ - 带有可变参数模板的 std::lock_guard

c++ - 在 2 个对象之间共享容器的提示?

c++ - 在 SOLARIS 上使用 C++ Pair 初始化 C++ std 映射时出错