我一直遇到STL排序问题。我正在尝试通过对象中的数据成员对对象矢量进行排序。我查了几个例子,但一旦它落入我的配置,它就不能在GCC下编译。我在Visual Studio上测试过它的工作原理。我在GCC上遇到这个错误:
no match for call to '(test::by_sym) (const stock&, const stock&)
我不明白的是,相同的代码将在Visual Studio上编译。
这是我的设置。
driver.cpp
DB t1;
t1.print();
cout << "---sorting---" << endl;
t1.sSort();
t1.print();
类DB
vector<stock> list;
struct by_sym {
bool operator()(stock &a, stock &b) {
return a.getSymbol() < b.getSymbol();
}
};
void DB::sSort(){
std::sort(list.begin(), list.end(), by_sym());
}
我的库存类只有数据成员。
海湾合作委员会是否有解决方法?
我相信我的问题类似于this,但那里的解决方案对我不起作用。
答案 0 :(得分:6)
您的operator()()
是不正确的。将其更改为
bool operator()(const stock& a, const stock& b) const
确保stock::getSymbol()
也是const
功能。如果不是,你不能改变它,那么按operator()()
的值取值,而不是(const)参考。
答案 1 :(得分:1)
错误消息说明了一切 - 显然G ++ STL实现期望比较谓词采用const参数。尝试将operator()的声明更改为
bool operator()(const stock &a, const stock &b)
并检查它是否有帮助。