对于使用地图,似乎需要比较功能。在下面的示例中,作为类成员的数组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];
}
};
提前谢谢。
答案 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];
}
};