繁体   English   中英

比较std :: lower_bound的函数

[英]Compare function for std::lower_bound

我有一个PersonsDB类,它的成员变量__emails应该是指向Person类(按Person电子邮件排序)的对象的指针的排序向量。 我的计划是使用带有自定义比较功能的lower_bound来获得在哪里插入下一个指针的迭代器。 成员函数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

}

我尝试遵循建议创建虚拟对象的答案 但是,我的代码无法编译并出现以下错误:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM