[英]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.