2016-01-20 112 views
3

我得到了矢量这种方式初始化vector<unique_ptr<Worker>> Workers。 Worker是一个具有私有字段名称的基类,它有两个派生类:Builder和Driver。排序的unique_ptr的向量

我添加到生成器的Workers矢量对象和驱动程序,然后我想用#include <algorithm>像这样按名称进行排序向量:

sort(Workers.begin(), Workers.end(), cmp_by_name); 


bool cmp_by_name(const Worker &a, const Worker &b) 
{ 
    return a.getName() < b.getName(); 
} 

但VS说

错误1错误C2664: 'bool(const Worker &,const Worker &)':无法将参数2从'std :: unique_ptr'转换为'const Worker &'c:\ program files(x86)\ microsoft visual studio 12.0 \ vc \ include \ algorithm 3071 1 A pp

你能帮我一下吗?

编辑:

感谢@NathanOliver,@ Rabbid76这个问题Sorting a vector of custom objects我编辑我cmp_by_name这种形式:

struct cmp_by_name 
    { 
     inline bool operator()(const unique_ptr<Worker>& a, const unique_ptr<Worker>& b) 
     { 
      return a->getName() < b->getName(); 
     } 
    }; 

我呼吁排序功能是这样的:

sort(Workers.begin(), Workers.end(), cmp_by_name()); 
+1

谓词的签名是错误的。 – Lingxi

回答

8

比较功能std::sort使用需要的形式为

bool cmp(const Type1 &a, const Type2 &b); 

其中类型Type1Type2必须使迭代器可以被解除引用,然后隐式转换为它们两者。

在你的情况下解引用Workers.begin()给你一个unique_ptr<Worker>而不是Worker。你需要改变你的比较函数采取const unique_ptr<Worker>&

在这种情况下,它也将结束寻找像

bool cmp_by_name(const std::unique_ptr<Worker>& a, const std::unique_ptr<Worker>& b) 
{ 
    return a->getName() < b->getName(); 
} 
+0

你能告诉我应该如何调用函数排序(Workers.begin(),Workers.end(),cmp_by_name);在这种情况下? –

+0

@DaArtagnan我不确定你的意思。如果你把'cmp_by_name'变成我在答案中的方式,那么它应该可以工作。 – NathanOliver

4

std::vector<std::unique_ptr<Worker>>的数据类型为std::unique_ptr<Worker>,所以你的比较函数必须是这样的:

bool cmp_by_name(const std::unique_ptr<Worker> &a, const std::unique_ptr<Worker> &b) 
{ 
    return a->getName() < b->getName(); 
} 

比较函数预期参数,以便在std::vector的对象可以转换到他们。