I declared a vector as follows: vector<unique_ptr<Worker>> Workers
. Worker
is a base class with a private field name
and it has two derived classes: Builder
and Driver
.
I add to the Workers
vector objects of Builder
and Driver
and then I want to sort the vector by name
using #include <algorithm>
like this:
sort(Workers.begin(), Workers.end(), cmp_by_name);
bool cmp_by_name(const Worker &a, const Worker &b)
{
return a.getName() < b.getName();
}
But the VS compiler says:
Error 1 error C2664: 'bool (const Worker &,const Worker &)' : cannot convert argument 2 from 'std::unique_ptr>' to 'const Worker &' c:\program files (x86)\microsoft visual studio 12.0\vc\include\algorithm 3071 1 App
How can I fix this error?
Thanks to @NathanOliver, @Rabbid76 and this question, I edited my cmp_by_name
into this form:
struct cmp_by_name
{
inline bool operator()(const unique_ptr<Worker>& a, const unique_ptr<Worker>& b)
{
return a->getName() < b->getName();
}
};
And I call the sort function like this:
sort(Workers.begin(), Workers.end(), cmp_by_name());