gpt4 book ai didi

c++ - 将下界与对象指针的 vector 一起使用

转载 作者:太空宇宙 更新时间:2023-11-04 12:49:47 24 4
gpt4 key购买 nike

我有这个数据结构:

class Person {
public:
string email, name, surname
};

class Bus {
vector<Person *> sortedbyemail;
vector<Person *> sortedbyname;
};

现在我想把指针添加到正确的位置,这样以后就不用再排序了。因为这导致我使用 lower_bound() 我完成了以下,甚至在我的 Add() 方法中没有可编译的代码:

bool Add(string name, string surname, string email) {
Person *p = new Person(name, surname, email);
auto it_l = lower_bound(
sortedbyemail.begin(), sortedbyemail.end(), email,
[](Person *x, Person *y) { return ((x->email) < (y->email)); });
}

现在,编译器向我抛出一个错误:“expected expression”带有指向比较方法中 [] 的箭头。此外,这不适合我的 OOP 方案,因为我需要允许公开电子邮件。

最佳答案

对于那些想知道的人,在这种情况下,lower_bound() 的第三个参数作为比较运算符的参数传递(它通常是一个函数)。如果你想像我一样使用两个对象指针进行比较,你需要使用类似这样的东西:

struct PersonMailComparator{
bool operator()( const Person * left, const Person * right )const
{
//try for yourself to figure out what you need here, for me it is:
return left->email.compare(right->email) < 0;
}
};

当向你的 vector 添加新的人物指针时

Person * p = new Person ( name, surname, email );
auto it_l = lower_bound( sortedbyemail.begin(), sortedbyemail.end(),
p, PersonMailComparator() );

关于c++ - 将下界与对象指针的 vector 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49581998/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com