Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing operator< in C++

I have a class with a few numeric fields such as:

class Class1 {
    int a;
    int b;
    int c;
public:
    // constructor and so on...
    bool operator<(const Class1& other) const;
};

I need to use objects of this class as a key in an std::map. I therefore implement operator<. What is the simplest implementation of operator< to use here?

EDIT: The meaning of < can be assumed so as to guarantee uniqueness as long as any of the fields are unequal.

EDIT 2:

A simplistic implementation:

bool Class1::operator<(const Class1& other) const {
    if(a < other.a) return true;
    if(a > other.a) return false;

    if(b < other.b) return true;
    if(b > other.b) return false;

    if(c < other.c) return true;
    if(c > other.c) return false;

    return false;
}

The whole reason behind this post is just that I found the above implementation too verbose. There ought to be something simpler.

like image 527
Agnel Kurian Avatar asked Jun 09 '10 13:06

Agnel Kurian


1 Answers

I assume you want to implement lexicographical ordering.

Prior to C++11:

#include <boost/tuple/tuple.hpp>
#include <boost/tuple/tuple_comparison.hpp>
bool Class1::operator<(const Class1& other) const
{
    return boost::tie(a, b, c) < boost::tie(other.a, other.b, other.c);
}

Since C++11:

#include <tuple>
bool Class1::operator<(const Class1& other) const
{
    return std::tie(a, b, c) < std::tie(other.a, other.b, other.c);
}
like image 143
avakar Avatar answered Sep 21 '22 20:09

avakar