sort()能对结构体排序吗?

shanfeib 2008-04-04 01:10:36
如现在有
stuct node
{
int me;
char * t;
double v[10];
};
现在我有struct node p[10];
如果要以结构体内的 me 为关键字来排序 p数组,这样可以用sort函数来实现吗?
如能,是怎么实现的呀?
如不能,可以用什么函数(STL提供的)来实现?
...全文
1623 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
yshuise 2008-04-04
  • 打赏
  • 举报
回复
stuct node 
{
private:
int me;
char * t;
double v[10];
public:
};
struct cmpnode{

template<typename T>
bool cmp(T* x, T* y){
return x->me < y->me;
}
};
vector<node*>rh;//楼主自己存放的指针
sort(rh.begin(), rh.end(), cmpnode::cmp<node>);
csdn5211 2008-04-04
  • 打赏
  • 举报
回复
有两种方法,一种是给node重载比较运算符<,还用一种是给sort指定一个用于比较的函数对象。

template<class RanIt>
void sort(RanIt first, RanIt last);
template<class RanIt, class Pred>
void sort(RanIt first, RanIt last, Pred pr);
The first template function reorders the sequence designated by iterators in the range [first, last) to form a sequence ordered by operator<. Thus, the elements are sorted in ascending order.

The function evaluates the ordering predicate X < Y at most ceil((last - first) * log(last - first)) times.

The second template function behaves the same, except that it replaces operator<(X, Y) with pr(X, Y).

yshuise 2008-04-04
  • 打赏
  • 举报
回复
stuct node 
{
private:
int me;
char * t;
double v[10];
public:
bool operator<(const node* rhs){
return this->me < rhs->me;
}
};
  • 打赏
  • 举报
回复

stuct node
{
int me;
char * t;
double v[10];
bool operator<( const node & )
};


template<class RandomAccessIterator, class Predicate>
void sort(
RandomAccessIterator _First,
RandomAccessIterator _Last,
Predicate _Comp //或者 自己提供sort的比较函数
);
abupie 2008-04-04
  • 打赏
  • 举报
回复
可以用sort().
struct也是一种class, 用sort()需要重载<,>运算。
搞什么哦 2008-04-04
  • 打赏
  • 举报
回复
可以
p[i].me
自己写个冒泡:
node d;
for(int i=0;i<10;i++)
for(int j=i+1;j<10;j++)
if(p[i].me>p[j].me)
d=p[i],p[i]=p[j],p[j]=d;

函数忘记了……

但愿没写错!

64,683

社区成员

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

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