标签:
sort的原型:
default (1) template <class RandomAccessIterator> void sort (RandomAccessIterator first, RandomAccessIterator last); custom (2) template <class RandomAccessIterator, class Compare> void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
说明:
string a[]={"1","3","2"}; vector<string> b(a,a+3); sort(b.begin(),b.end()); //sort(b.begin(),b.end(),less<string>()); the same
定义排序函数:
方法1:声明外部比较函数
bool Less(const Student& s1, const Student& s2) { return s1.name < s2.name; //从小到大排序 } std::sort(sutVector.begin(), stuVector.end(), Less);
注意:比较函数必须写在类外部(全局区域)或声明为静态函数
当comp作为类的成员函数时,默认拥有一个this指针,这样和sort函数所需要使用的排序函数类型不一样。
否则,会出现错误
class Leg { public: int length; int cost; Leg(int x,int y):length(x),cost(y){} bool operator < (const Leg& a) const //不加const会报错的 { return length<a.length; } bool operator=(const Leg& a)const { return length==a.length; } };
方法2:重载类的比较运算符
bool operator<(const Student& s1, const Student& s2) { return s1.name < s2.name; //从小到大排序 } std::sort(sutVector.begin(), stuVector.end());
方法3:声明比较类
struct Less { bool operator()(const Student& s1, const Student& s2) { return s1.name < s2.name; //从小到大排序 } }; std::sort(sutVector.begin(), stuVector.end(), Less());
标签:
原文地址:http://www.cnblogs.com/daocaorenblog/p/5381883.html