-2
我想根据它们的ID对对象列表进行排序。如何根据对象的属性对对象列表进行排序?
当我创建的对象的Id的列表进行比较的功能,它得到的错误:
Severity Code Description Project File Line Suppression State
Error C3867 'BobControl::compareId': non-standard syntax; use '&' to create a pointer to member list.sort c:\users\wil\documents\visual studio 2015\projects\list.sort\list.sort\source.cpp 32
此代码是用来测试的问题。
#include <iostream>
#include <list>
#include <string>
using namespace std;
class Bob {
public:
Bob::Bob(int id) {
_id = id;
}
int getId() const { return _id; }
private:
int _id = 0;
};
//testing lists
class BobControl {
public:
bool compareId(const Bob& first, const Bob& second)
{
return (first.getId() < second.getId());
}
void testCompar() {
bobs.sort(compareId);
}
void controlBobs() {
list<Bob>::iterator lit;
bobs.push_back(Bob(0));
bobs.push_back(Bob(1));
bobs.push_back(Bob(5));
bobs.push_back(Bob(3));
testCompar();
for (lit = bobs.begin(); lit != bobs.end(); lit++) {
cout << (*lit).getId() << endl;
}
}
private:
list<Bob> bobs;
};
int main() {
BobControl bobc;
bobc.controlBobs();
system("PAUSE");
return 0;
}
如果要排序对象,请尝试使用算法排序。这样就变得简单了 – AchmadJP
@AchmadJP:'std :: list'有自己的['sort()'](http://en.cppreference.com/w/cpp/container/list/sort)方法。 'std :: sort()'不是比'std :: list :: sort()'更容易使用的。他们都有MichaelAlbers的回答中提到的相同限制。 –