我有一个 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/