【发布时间】:2020-03-17 15:26:41
【问题描述】:
尝试在不考虑 std::set 容器的对象的排列(必须将其视为重复项:因此顺序不重要)的情况下实现 4 个对象的组合,一次取 2 个对象:
struct Combination {
int m;
int n;
Combination(const int m, const int n):m(m),n(n){}
};
const auto operator<(const auto & a, const auto & b) {
//explicitly "telling" that order should not matter:
if ( a.m == b.n && a.n == b.m ) return false;
//the case "a.m == b.m && a.n == b.n" will result in false here too:
return a.m == b.m ? a.n < b.n : a.m < b.m;
}
#include <set>
#include <iostream>
int main() {
std::set< Combination > c;
for ( short m = 0; m < 4; ++ m ) {
for ( short n = 0; n < 4; ++ n ) {
if ( n == m ) continue;
c.emplace( m, n );
} }
std::cout << c.size() << std::endl; //12 (but must be 6)
}
预期的组合集是0 1、0 2、0 3、1 2、1 3、2 3,这是其中的 6 个,但结果是 c.size() == 12。另外,我的operator<(Combination,Combination) 确实满足!comp(a, b) && !comp(b, a) means elements are equal 的要求。
我错过了什么?
【问题讨论】: