如何用std::sort对自定义结构的vector以关键字来排序

xpaul 2003-10-14 01:09:30
struct pcb {
int id;
int needtime;
int startime;
int endtime;
bool state;
};

如何对vector<pcb>以pcb.needtime的大小来排
...全文
1079 12 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
ttlb 2003-10-26
  • 打赏
  • 举报
回复
up
Wolf0403 2003-10-26
  • 打赏
  • 举报
回复
个人感觉我的写 function object 的方法是最好的:不需要修改原理的类设计。

killme2008 2003-10-26
  • 打赏
  • 举报
回复
cfpp1234(cfpp1234
谢谢了
to Wolf0403(完美废人)
function obeject怎么写??

cfpp1234 2003-10-25
  • 打赏
  • 举报
回复
你可在struct內加入 operator < ,就可以使struct有排序能力.
因為而你的pcd struct內沒有指針,所以不須要有copy constructor
和copy assignment, 編譯器會為你提供的, 你不須要自己做的.
當你要排序時只要寫 sort( obj.begin(), obj.end() )就可.
以下的main做了一個試範.

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

struct pcb {
int id;
int needtime;
int startime;
int endtime;
bool state;

bool operator< ( const pcb& rhs ) const {
return needtime < rhs.needtime;
}
};

int main()
{
vector<pcb> ctn ;

for ( int i=0; i<10; i++ ) {
pcb po ;
po.needtime = int(((double)rand() / RAND_MAX) * 100) ;
ctn.push_back(po) ;
}

sort( ctn.begin(), ctn.end() ) ;

for ( i=0; i<10; i++ )
printf("%d\n",ctn[i].needtime);


return 0 ;
}
killme2008 2003-10-25
  • 打赏
  • 举报
回复
关注
高手给个例子吧
Robin 2003-10-15
  • 打赏
  • 举报
回复
:》
Overload Operator<
rainwolfchen 2003-10-14
  • 打赏
  • 举报
回复
如果要自己定义STL容器的元素类最好满足STL容器对元素的要求
必须要求:
1、Copy构造函数
2、赋值=操作符
3、能够销毁对象的析构函数

另外:
1、可用的缺省构造函数,序列型容器必须,用于初始化元素
2、==操作符定义,用于判断相等
3、<操作符定义,关联型容器必须,用于缺省排序
Phenix206 2003-10-14
  • 打赏
  • 举报
回复
inline bool operator<(const pcb& lsh, const pcb& rsh)
{
return lsh.needtime < rsh.needtime;
}
fangrk 2003-10-14
  • 打赏
  • 举报
回复
struct pcb {
int id;
int needtime;
int startime;
int endtime;
bool state;
bool ByNeedTime(const pcb& rhs) const
{
return needtime < rhs.needtime;
}
};

vector<pcb> V;
...
sort(V.begin(),V.end(),mem_fun_ref(&pcb::ByNeedTime));

如果无法编译,尝试
#include <functional>
#include <algorithm>
Wolf0403 2003-10-14
  • 打赏
  • 举报
回复
std::sort 要求的是 random_access_iterator, vector 刚好合适。
既然是 C++,struct 也可以重载 operator< 的。或者另外一个方法:
自己写一个比较函数对象
A binary predicate takes two arguments and returns true when satisfied and false when not satisfied.
例如:
struct PcbCompair
{
bool operator()(const pcb& a, const pcb& b)
{
return a.needtime < b.needtime;
}
};
没有调试,详见 MSDN 2003 APRIL
ms-help://MS.MSDNQTR.2003APR.1033/vcstdlib/html/vclrfAlgorithmSort.htm
sevencat 2003-10-14
  • 打赏
  • 举报
回复
既然都要排序了,用VECTOR可能不是很恰当的。
rtdb 2003-10-14
  • 打赏
  • 举报
回复
最好把 struct 换成class, 然后重载 < 就可以了


24,860

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 工具平台和程序库
社区管理员
  • 工具平台和程序库社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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