简体   繁体   中英

c++ how to send object pointer to function (sort list of pointers )

I am using

std::list<Employee*> Employees;

Employee is a class so my proplem is that i need to sort list, and for doing that i must define operator < but i don't know how to define the operator to take Employee* object this is my define

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

but its work only for Employee < Employee* but i need the operator to work on Employee* < Employee*

or if there anther solution for sorting the list well help

You don't need to provide operator< , and you can't, with both arguments being pointers (they are considered as a built-in type, and there already is a built-in operator< that the language won't let you change).

Use the second std::list::sort overload instead, with a custom comparison function
(a non-member function with two parameters):

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

or a lambda function defined in-place:

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

You should understand what your code above does. It allows you to compare const Employee with Employee const* , in this order. They're not both pointers. It is also preferred to overload binary operators as non-member functions .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM