c++ - “no match for ' operator< '” 尝试插入到 std::set 时

标签 c++ stl set

我正在使用 gcc 4.3.3 尝试编译以下代码:

struct testStruct {  
int x;  
int y;  
bool operator<(testStruct &other) { return x < other.x; }  
testStruct(int x_, int y_) {  
    x = x_;  
    y = y_;  
}  
};  


int main() {
multiset<testStruct> setti;  
setti.insert(testStruct(10,10));  
return 0;  
}

我得到这个错误:
/usr/include/c++/4.4/bits/STL_function.h|230|错误:‘__x < __y’中的‘operator<’不匹配
我怀疑我没有像应该做的那样重载运算符,但我无法查明确切的问题。我在这里做错了什么?

最佳答案

运算符必须是 const 并且取一个 const 引用:

bool operator<(const testStruct &other) const { return x < other.x; }  

关于c++ - “no match for ' operator< '” 尝试插入到 std::set 时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3214569/

相关文章:

c++ - 使用 unordered_map,其中 Key 是 T 的成员

c++ - STL 标准判断哪些算法有拷贝版本,哪些没有?

java - 集合和哈希集 Java

java - 在我的例子中使用 Set 删除数组中的重复元素

c++ - “可变”变量只能通过一种 const 方法可变吗?

C++0x 实现猜测?

c++ - 为什么编写反向迭代器会影响迭代器是否是随机访问迭代器?

batch-file - 在 if 语句内的设置变量内扩展 %userprofile%。批

c++ - 在 Linux 中动态排列应用程序窗口

c++ - 为什么在没有参数的情况下调用省略号而不是可变参数模板?