2013-07-27 64 views
0

在一些stdtemplate的参数,一个需要定义他/她自己的功能比较less(a, b)more(a, b)然后std::some_template<T, *, myComparator()>,但是为什么呢?为什么我们仍然需要我们自己定义的功能比较

+1

什么是 “STL”? – 2013-07-27 14:17:45

+0

所有的大多数都有它们的默认比较器。 它全部在程序员的意图 – P0W

+0

@ H2CO3我不知道该给这个词打什么电话,这就是为什么我只是称它为stl,对不起 – mr5

回答

5

比较器的目的是允许排序的stl容器中的对象排序。如果默认的比较器不适合容器所容纳的对象类型,则只需要提供自己的比较器。

例如,如果您要制作以下struct的std :: set,那么您需要编写自己的比较器。

struct Person 
{ 
    std::string first_name, last_name, phone_number; 
} 

默认比较器知道如何比较数字和字符串,但它不知道如何比较Person对象。这是如何编写自定义比较器来按last_name排序Person对象的。

struct Person_Comparator 
{ 
    bool operator()(const Person &a, const Person &b) const { 
     return a.last_name < b.last_name; 
    } 
}; 
1

又如让让一组具有一些不同的标准

int main() 
{ 
    //By default set will use std::less<int>() 
    //Lets make a set based on no. of 1's in binary representation of elements 

    set<int,mycomp> s; 
    for(auto i=1;i<20;i++) //Note :Duplicates 1's representation will be discarded 
     s.insert(i); 

    for(auto i:s) 
     cout<<i<< " "; //19 15 8 7 3 1 
    return 0; 
} 

以及相应的比较会像下面:

struct mycomp 
{ 
    bool operator()(const int& a, const int& b) const { 
     auto count_bits = [](long n){ 
      unsigned int c; 
      for (c = 0; n; c++) 
      n &= n - 1; 
      return c; 
     }; 
      return count_bits(a) != count_bits(b); 
     } 
}; 
0

我们仍然偶尔也需要我们自己定义的函数比较器在泛型编程中,但我们并不总是需要自己编写:)你可以使用这个在线向导[http://www.xochellis.org/genericdataordering/wizard .php],以创建严格的弱命令函子,或者你需要的lambda。

例如,在上一个答案的示例Person_Comparator中,您只需填写向导窗体中的三个字段,如this picture所示。

欲了解更多详细信息,您可以参考here还有:

最好的问候, 吉姆Xochellis

相关问题