2011-08-01 28 views
3
class Message 
{ 
    public: 
     std::string getHeader (const std::string& header_name) const; 
     // other methods... 
}; 

class MessageSorter 
{ 
    public: 
     // take the field to sort by in the constructor 
     MessageSorter (const std::string& field) : _field(field) {} 
     bool operator (const Message& lhs, const Message& rhs) 
     { 
      // get the field to sort by and make the comparison 
      return lhs.getHeader(_field) < rhs.getHeader(_field); 
     } 
    private: 
     std::string _field; 
}; 

std::vector<Messages> messages; 
// read in messages 
MessageSorter comparator; 
sort(messages.begin(), messages.end(), comparator); 

对于此行: 布尔运算符(const的消息& LHS,常量消息&右)关于产品()运算符重载

这是正确? 它应该是 布尔运算符()(常量消息& LHS,常量消息&右)

该代码可用于函子的教程exmample代码。 可以在这里看到: http://www.cprogramming.com/tutorial/functors-function-objects-in-c++.html

谢谢

+1

尼斯从**书本学习C++ **。通常没有太多的错别字。 – Schnommus

回答

3

你猜对了 - 这可能是一个错字,应该读

bool operator()(const Message& lhs, const Message& rhs) 
+1

也许应该标记为'const'。 –

+0

@Ben Yeah,这是一个好主意,但我只想解决他的问题。有时难以回答关于SO的问题,也不想提供大量无关的建议:) – Josh