Lower than operator for structs

时间:2016-10-15 17:11:58

标签: c++ struct c++98

I've got a struct containing two data types that have the lower than, greater than and equals operators implemented. I want to implement the lower than operator for my struct:

struct number_pair
{
    int a;
    int b;
    bool operator<(const pair& other) const { return ?; }
}

You need to be able to sort multiple instances of the struct using the operator. The order should respect both a and b. I don't want to use libraries other than std and I'm on C++98 so std::tuple is not available.

Is it possible to achieve what I want if the two data types only have the lower than, greater than and equals operators implemented? If thats the case, how would the implementation of the operator look, and otherwise, what else would you need to know about the data types to implement the operator?

3 个答案:

答案 0 :(得分:3)

To help to undestand the underlying concept, consider a simpler case of comparing two text strings. Ask yourself, how do you compare two strings? You should know the answer: compare the first character of each string. If they're the same, move on to the second character, and so on. I'm leaving out the details of handling strings that differ in length, but that's the basic underlying concept.

Here, the concept is exactly the same if you consider that you always have a two character string, and mentally substitute the two character with your a and b:

bool operator<(const pair& other) const {
   if (a != other.a)
       return a < other.a
   return b < other.b;
}

This will be sufficient, for this simple use case. When dealing with templates and other complex types, for various reasons one often has to use only the < operator. If you impose the same artificial restriction, on yourself, of implementing your custom operator< only in terms of < itself, then:

bool operator<(const pair& other) const {
   if (a < other.a)
       return true;
   if (other.a < a)
       return false;
   return b < other.b;
}

答案 1 :(得分:3)

You want lexicographical comparison. There's a C++ function for this: std::lexicographical_compare. This algorithm is the same one that's used for sorting std::tuple objects.

You can easily implement this yourself (without std::lexicographical_compare) like so:

struct pair {
    int a;
    int b;
    bool operator<(const pair& other) const {
        return a < other.a || (a == other.a && b < other.b);
    }
};

Alternatively, you can use std::pair<int, int> to do this. It's already got a lexicographical-order operator< defined.

答案 2 :(得分:0)

虽然可能无法使用std::tuple,但您仍然可以使用boost::tupleboost::tie

#include <boost/tuple/tuple.hpp>
#include <boost/tuple/tuple_comparison.hpp>

struct number_pair
{
    int a;
    int b;
    bool operator<(const number_pair& other) const {
        return boost::tie(a, b) < boost::tie(other.a, other.b);
    }
};