2016-11-14 52 views
0

std::map(函数省略)中,实现'<'运算符使用以下简单类作为键的正确方法是什么?实现'<'运算符

class Person 
{ 
public: 
    bool valid = false; 
    std::string name = ""; 
    std::string id = ""; 
} 
+0

不是欺骗,但一个很好的参考:HTTP:// stackoverflow.com/questions/4421706/operator-overloading – NathanOliver

+0

你有一个名为'id'的字段。它的名字暗示它是独一无二的。是吗?如果是这样,你可以利用这个事实。 – hvd

+0

没有“正确的”方法。只要它满足*严格的弱排序*,它就取决于你。 – juanchopanza

回答

4

您可以使用std::tie

class Person 
{ 
public: 
    bool valid = false; 
    std::string name = ""; 
    std::string id = ""; 

    bool operator<(const Person& r) const 
    { 
     return std::tie(valid, name, id) < std::tie(r.valid, r.name, r.id); 
    } 
} 

说明:

std::tie(xs...)创建于通过xs...参数引用的std::tupleComparison between two std::tuple instances作品按字典顺序排列比较元素,从而为您的类型提供排序。

更多信息here on cppsamplesin this question

+0

哈哈!英雄所见略同。 –

+2

@RichardHodges:现在让我们争取**会员功能** vs **免费功能**! –

+0

更好地解释如何/为什么'领带'是要走的路/它在做什么。 – NathanOliver

2
#include <string> 
#include <tuple> 

class Person 
{ 
public: 
    bool valid = false; 
    std::string name = ""; 
    std::string id = ""; 
}; 

bool operator<(const Person& l, const Person& r) 
{ 
    return std::tie(l.valid, l.name, l.id) < std::tie(r.valid, r.name, r.id); 
} 
4

您可以使用std::tie其他答案建议。如果你想清楚地看到逻辑在自己的功能或没有访问C++编译器11,可以实现它:

class Person 
{ 
    public: 
     bool valid = false; 
     std::string name = ""; 
     std::string id = ""; 

     bool operator<(Person const& rhs) const 
     { 
     if (this->valid != rhs.valid) 
     { 
      return (this->valid < rhs.valid); 
     } 
     if (this->name != rhs.name) 
     { 
      return (this->name < rhs.name); 
     } 
     return (this->id < rhs.id); 
     } 
}; 
+0

如果是我,我会做到这一点,因此所有无效对象都是等效的,而不依赖于其他成员。这是你无法用'std :: tie'完成的事情。 –

+1

应该指出的是,'std :: tuple'使用等同性,而这个实现使用相等性。这些类型是一样的,但不是一般的。 – StoryTeller