【问题标题】:c++ how to send object pointer to function (sort list of pointers )c ++如何将对象指针发送到函数(指针列表排序)
【发布时间】:2018-11-12 07:04:19
【问题描述】:

我正在使用

std::list<Employee*> Employees;

Employee 是一个类 所以我的问题是我需要对列表进行排序,为此我必须定义运算符

bool operator <(const Employee *_employee) const { return (id < _employee->id); }

但它仅适用于 Employee &lt; Employee*,但我需要操作员在 Employee* &lt; Employee* 上工作

或者如果有其他解决方案可以很好地帮助列表排序

【问题讨论】:

    标签: c++ visual-c++ stl operator-overloading operators


    【解决方案1】:

    您不需要提供operator&lt;you can't, with both arguments being pointers(它们被视为内置类型,并且已经存在语言不允许您更改的内置operator&lt;) .

    请改用second std::list::sort overload,并使用自定义比较函数
    (具有两个参数的非成员函数):

    bool employee_ptr_cmp(Employee const* lhs, Employee const* rhs) { ... }
    ...
    Employees.sort(employee_ptr_cmp);
    

    或就地定义的 lambda 函数:

    Employees.sort([](Employee const* lhs, Employee const* rhs) { ... });
    

    你应该明白你上面的代码是做什么的。它允许您按此顺序比较const EmployeeEmployee const*。他们不是两个指针。也首选overload binary operators as non-member functions

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多