使用下界与对象指针的向量

时间:2018-03-30 22:04:05

标签: c++ vector lower-bound

我有这个数据结构:

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)); });
}

现在,编译器向我抛出一个错误:&#34;期望的表达式&#34;在compare方法中用箭头指向[]。此外,这不适合我的OOP方案,因为我需要允许电子邮件公开。

1 个答案:

答案 0 :(得分:0)

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

master [localhost] {root} (performance_schema) > select version();
+------------+
| version()  |
+------------+
| 5.7.20-log |
+------------+

master [localhost] {root} (performance_schema) > alter table events_statements_summary_by_thread_by_event_name add primary key (thread_id, event_name);
ERROR 1044 (42000): Access denied for user 'root'@'localhost' to database 'performance_schema'

master [localhost] {root} (performance_schema) > show grants;
+---------------------------------------------------------------------+
| Grants for root@localhost                                           |
+---------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION |
| GRANT PROXY ON ''@'' TO 'root'@'localhost' WITH GRANT OPTION        |
+---------------------------------------------------------------------+

以及向向量添加新人指针

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;
  }
};