为什么下面的程序不能工作?我怎么才能修复它?
#include <iostream>
#include <set>
using namespace std;
class K {
private:
    long a;
};
int main ()
{   
    K a;
    set<K> b;
    b.insert(a);
    return 0;
}发布于 2011-03-29 00:26:56
std::set需要对元素进行排序。它要求您可以按照某种顺序比较它的元素。
或者为您的类K添加一个operator <,或者向set类提供第二个模板参数--比较器,该参数决定两个K实例之间的顺序。
重载operator <很简单:
bool operator <(K const& x, K const& y) {
     return x.a < y.a;
}这意味着当且仅当其成员a小于另一个的成员时,一个K实例才小于另一个实例。
发布于 2011-03-29 00:38:06
set要求您的类定义了operator<。例如:
class K {
public:
bool operator< (const K& other) const {
    return this->a < other.a;
}
private:
long a;
};https://stackoverflow.com/questions/5462032
复制相似问题