c ++ map class as key:将函数与递归函数进行比较

时间:2017-04-20 07:42:05

标签: c++ dictionary

对于使用地图,似乎需要比较功能。在下面的示例中,作为类成员的数组c具有四个元素c [4]。

问题]当c [100]时,编写'运算符<'的最佳方式是什么?以一种紧凑的方式?

class Configuration {
public:
    int c[4];
    bool operator<(const Configuration& other) const {
        if(c[0] == other.c[0]) {
            if(c[1] == other.c[1]) {
                if(c[2] == other.c[2]) {
                    return c[3] < other.c[3];
                }
                return c[2] < other.c[2];
            }
            return c[1] < other.c[1];
        }
        return c[0] < other.c[0];
    }
};

提前谢谢。

3 个答案:

答案 0 :(得分:2)

这是std::array 更好的众多地方之一。

class Configuration {
public:
    std::array<int, 100> c;
    bool operator<(const Configuration& other) const {
        return c < other.c
    }
};

答案 1 :(得分:2)

这有一个标准功能:lexicographical_compare(std::begin(c), std::end(c), std::begin(other.c), std::end(other.c))

答案 2 :(得分:0)

class Configuration {
public:
    int N = 100;
    int c[N];
    bool operator<(const Configuration& other) const {
        int i = 0;
        for (; i != (N - 1); ++i) {
            if (c[i] != other.c[i]) break;
        }
        return c[i] < other.c[i];
    }
};