我一直在STL排序问题。我正在尝试按对象中的数据成员对对象 vector 进行排序。我查看了几个示例,但是一旦它落入我的配置中,就无法在GCC下编译。我在Visual Studio上进行了测试,并且可以正常工作。我在GCC上收到此错误:
no match for call to '(test::by_sym) (const stock&, const stock&)
我不明白的是,相同的代码将在Visual Studio上编译。

这是我的设置。

驱动程序

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());
}

而我的股票类中只有数据成员。

在GCC上有解决方法吗?

我相信我的问题类似于this,但是那里的解决方案对我不起作用。

最佳答案

您的operator()()是const不正确的。更改为

bool operator()(const stock& a, const stock& b) const

确保stock::getSymbol()也是const函数。如果不是,并且您无法更改它,则按值而不是(const)引用采用operator()()的参数。

10-06 05:06
查看更多