如何利用C++/STL vector的sort算法对元素是自定义类型进行排序?
STL中提供了高效的排序算法,vector中是sort函数。当vector的元素数据类型是基本数据类型(int,double)时自然可以调用sort进行排序。但是当vector的元素是我们自定义的类或结构类型呢?如定义class Student{ public string name;public double score;}定义vector<Student> stuVector;想对stuVector按照score成绩进行排序该如何做呢?无法利用STL提供的算法,必须自己手动实现排序吗?
在C#中为Student实现IEnumerable借口就能调用类库算法了,C++中有这样的功能么?
说的有点啰嗦,但是相信大家还是能够理解的,在此先谢过了~~~
[解决办法]
定义排序函数:
bool Less(const Student& s1, const Student& s2)
{
return s1.name < s2.name; //可以自己设定
}
std::sort(sutVector.begin(), stuVector.end(), Less);
或者
bool operator<(const Student& s1, const Student& s2)
{
return s1.name < s2.name; //可以自己设定
}
std::sort(sutVector.begin(), stuVector.end());
或者
struct Less
{
bool operator()(const Student& s1, const Student& s2)
{
return s1.name < s2.name; //可以自己设定
}
};
std::sort(sutVector.begin(), stuVector.end(), Less());
//或重载student的operato<
[解决办法]
struct myclass {
bool operator() (int i,int j) { return (i<j);}
} myobject;
在你的结构体理,加上这么一个函数~~~
[解决办法]