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

list的排序有关问题. (续)

2012-02-29 
list的排序问题. (续)#includelist using namespace stdstruct student{int idchar name[20]}bool c

list的排序问题. (续)
#include <list > 
using namespace std; 

struct student 

int id; 
char name[20]; 
}; 

bool compfn(student x,student y) 

if(x.id > y.id) 
return true; 
else 
return false; 


void main() 

list <student > l; 
student st; 

st.id = 1; 
strcpy(st.name,"aaa"); 
l.push_back(st); 
st.id = 3; 
strcpy(st.name,"bbb"); 
l.push_back(st); 
st.id = 2; 
strcpy(st.name,"ccc"); 
l.push_back(st); 

l.sort(compfn); 


编译不过: 
error C2664: 'void __thiscall std::list <struct student,class std::allocator <struct student > >::sort(struct std::greater <struct student >) ' : cannot convert parameter 1 from 'bool (struct student,struct student) ' to 'struct  
std::greater <struct student > ' 

怎样修改?

有人说是VC6的BUG,建议如下修改:
struct compfn 

bool operator ()(student &x,student &y) 

if(x.id > y.id) 
return true; 
else 
return false; 

}; 

然后调用sort的语句改为l.sort(compfn()); 
但还是编译不过:

error C2664: 'void __thiscall std::list<struct student,class std::allocator<struct student> >::sort(struct std::greater<struct student>)' : cannot convert parameter 1 from 'struct compfn' to 'struct std::greater<s
truct student>'
  No constructor could take the source type, or constructor overload resolution was ambiguous

http://topic.csdn.net/u/20071016/23/ef0602c3-c926-4780-ba7e-d67c94618347.html


[解决办法]
刚才的方法在g++下面没问题,
VC6下面你用下面的方法,不用定义compfn
bool operator > (student const& x, student const& y)
{
if(x.id > y.id) 
return true; 
else 
return false;
}
l.sort(std::greater<student>());
这样改应该没问题了吧

热点排行