sort算法的问题

bg205 2006-03-25 08:27:33
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
//自定义类型
struct MyStruct
{
unsigned long int id;
unsigned long int cost;
};

typedef MyStruct elemType;

bool cmp(elemType&,elemType&);
void Print(const elemType&);

int main()
{
elemType tempData;
unsigned long int id,cost;
ifstream fin("data.txt");
vector<elemType> soureList;
while(fin>>id)
{
fin>>cost;
tempData.id=id;
tempData.cost=cost;
soureList.push_back(tempData);
}
cout<<"原始数据:"<<endl;
for_each(soureList.begin(),soureList.end(),Print);
sort(soureList.begin(),soureList.end(),cmp); //问题出现在此处???
cout<<"按id升序排序后的数据:"<<endl;
for_each(soureList.begin(),soureList.end(),Print);;
return 0;
}
//按id升序排序
bool cmp(elemType& a, elemType& b)
{
return (a.id<b.id);
}

void Print(const elemType& data)
{
cout<<data.id<<" "<<data.cost<<endl;
}



我的程序编译到此出问题sort(soureList.begin(),soureList.end(),cmp); //问题出现在此处???
...全文
215 8 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
bg205 2006-03-26
  • 打赏
  • 举报
回复
xlsue(小林) ( ) 信誉:100 2006-03-25 21:37:00 得分: 0


以前碰到过类似的问题。是参数不匹配,就是我所说的那个函数,参数要改为 const T& 形式


正解
xiao2004 2006-03-26
  • 打赏
  • 举报
回复
顺便说一声,为什么要加个const
xlsue 2006-03-25
  • 打赏
  • 举报
回复
以前碰到过类似的问题。是参数不匹配,就是我所说的那个函数,参数要改为 const T& 形式
xlsue 2006-03-25
  • 打赏
  • 举报
回复
不同的编译器的实现不同。你的编译器在内部调用这个一个函数:
template<typename _Tp, typename _Compare>
inline const _Tp&
__median(const _Tp& __a, const _Tp& __b, const _Tp& __c, _Compare __comp)
{
// concept requirements
__glibcxx_function_requires(_BinaryFunctionConcept<_Compare,bool,_Tp,_Tp>)
if (__comp(__a, __b))
if (__comp(__b, __c))
return __b;
else if (__comp(__a, __c))
return __c;
else
return __a;
else if (__comp(__a, __c))
return __a;
else if (__comp(__b, __c))
return __c;
else
return __b;
}
Could 2006-03-25
  • 打赏
  • 举报
回复
我用vc2005,运行你的代码无问题。
xlsue 2006-03-25
  • 打赏
  • 举报
回复
改为:bool cmp(const elemType& a, const elemType& b) 看看
逸学堂 2006-03-25
  • 打赏
  • 举报
回复
没有看出问题来。
lz 的print能打印函数吗?
bg205 2006-03-25
  • 打赏
  • 举报
回复
我的编译器是gcc

65,198

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧