c++STL中的sort()函数 能对链表进行排序吗?
boolCmp(T*a,T*b){returna->age>b->age;}我已经建好了一个链表,要按年龄排序,能这样写吗?sort(Head,End,Cmp);求教高手...
bool Cmp( T *a, T *b)
{
return a->age > b->age;
}
我已经建好了一个链表,要按年龄排序,能这样写吗?
sort(Head, End, Cmp);
求教高手! 展开
{
return a->age > b->age;
}
我已经建好了一个链表,要按年龄排序,能这样写吗?
sort(Head, End, Cmp);
求教高手! 展开
4个回答
展开全部
sort函数的两个参数是迭代器,另外一个回调函数或仿函数可以自己定义。
#include <algorithm>
template <class RandomAccessIterator>
void sort( RandomAccessIterator start, RandomAccessIterator end );
template <class RandomAccessIterator, class Compare>
void sort( RandomAccessIterator start, RandomAccessIterator end, Compare cmp );
//************
The sort algorithm sorts the elements in the range [start,end) into ascending order. If two elements are equal, there is no guarantee what order they will be in.
If the function object cmp is given, then it will be used to compare two objects instead of the < operator. cmp should induce a strict weak ordering on the values from start to end.
Note that sort will only work with RandomAccessIterators. For example, you cannot use sort on the iterators of a list; you should use list::sort instead.
Parameters
start and end are RandomAccessIterators pointing to the range of elements to be sorted.
cmp is an optional function object that is used in place of < to perform comparisons between pairs of elements
#include <algorithm>
template <class RandomAccessIterator>
void sort( RandomAccessIterator start, RandomAccessIterator end );
template <class RandomAccessIterator, class Compare>
void sort( RandomAccessIterator start, RandomAccessIterator end, Compare cmp );
//************
The sort algorithm sorts the elements in the range [start,end) into ascending order. If two elements are equal, there is no guarantee what order they will be in.
If the function object cmp is given, then it will be used to compare two objects instead of the < operator. cmp should induce a strict weak ordering on the values from start to end.
Note that sort will only work with RandomAccessIterators. For example, you cannot use sort on the iterators of a list; you should use list::sort instead.
Parameters
start and end are RandomAccessIterators pointing to the range of elements to be sorted.
cmp is an optional function object that is used in place of < to perform comparisons between pairs of elements
展开全部
sort算法的迭代器用的是随机访问迭代器,链表的不是,因此不能用该算法,数组和vector可以
楼上的英文就是这个意思:RandomAccessIterator
楼上的英文就是这个意思:RandomAccessIterator
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
sort算法的迭代器用的是随机访问迭代器(RandomAccessIterator ),链表的不是,因此不能用该算法,数组和vector可以.
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
如果,你建立的是个链表的类,sort()就可以直接用对象进行调用成员a.sort(),一般不用参数
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询