std::lower_bound 的比较函数

Compare function for std::lower_bound

我有一个 class PersonsDB,其成员变量 __emails 应该是指向 class Person 对象的指针的排序向量(按 Person 电子邮件排序)。我的计划是将 lower_bound 与自定义比较函数一起使用,以获得插入我的下一个指针的位置的迭代器。 成员函数email() returns只是一个字符串。

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,不需要命名函数。