首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

一个关于sort算法的有关问题

2012-02-23 
一个关于sort算法的问题#includeiostream#includevector#includealgorithm#includefunctionalusin

一个关于sort算法的问题
#include   <iostream>
#include   <vector>
#include   <algorithm>
#include   <functional>

using   namespace   std;

class   student{
public:
student(int   a=0):data(a){   }
void   print(){   cout < <data < <endl;   }
bool   operator==(const   student   &stu){
return   data==stu.data;
}
bool   operator <(const   student   &stu){
if   (data <stu.data)
return   true;
else   return   false;
}
bool   operator> (const   student   &stu){
return   data> stu.data;
}

private:
int   data;
};  

int   main(){
vector <student>   stu;
stu.push_back(student(32));
stu.push_back(student(100));
stu.push_back(student(3));
sort(stu.begin(),   stu.end());
vector <student> ::iterator   ite=stu.begin();
for   (   ;   ite <stu.end();   ++ite)
(*ite).print();
sort(stu.begin(),   stu.end(),   greater <student>   ());
for   (ite=stu.begin();   ite <stu.end();   ++ite)
ite-> print();
}

上面上我写的一个student类,   可是在编译的时候总是说下面这条语句出了问题
sort(stu.begin(),   stu.end(),   greater <student>   ());
明明我已经写了 <,   > ,   ==的运算符重载了嘛.  
可是为什么还是有问题呢?



[解决办法]
sort函数内部将使用const对象调用相关的运算符,而你原来的operator > 不是const函数,不能从const成员上调用。

热点排行