C++使用sort()排序Event对象时遇‘operator<不匹配’错误
问题分析与解决
你的错误根源在于重载的<运算符没有被声明为const成员函数。
在lambda表达式里,lhs和rhs都是const Event&类型的引用——const对象只能调用const修饰的成员函数,而你当前的operator<成员函数没有const限定,编译器找不到可以匹配的函数,因此抛出no match for 'operator<'错误。
修复步骤
1. 修改Event.h中的运算符声明
在声明末尾加上const关键字:
bool operator<(const Event&) const;
2. 修改Event类中运算符的实现
同样在函数参数列表后加上const:
bool Event::operator<(const Event &rhs) const { if (yearnum < rhs.year()) { return true; } else if (yearnum == rhs.year() && monthnum < rhs.month()) { return true; } else if (monthnum == rhs.month() && daynum < rhs.day()) { return true; } else { return false; } }
额外优化建议
你当前每次push_back一个元素后就调用sort,这种做法效率很低——可以等所有元素都读取完成后再一次性排序,避免多次重复排序的开销:
void Schedule::read(istream &in) { string s; while (in >> s) { try { Event e(s); events.push_back(e); } catch(...) { in.setstate(ios::failbit); throw; } } // 所有元素读取完成后再排序,无需自定义lambda sort(events.begin(), events.end()); }
内容的提问来源于stack exchange,提问作者Tyler
相关产品推荐
相关产品推荐

