学习要点:
1 sort函数 和其它函数,包括 STL容器等 表示区间都是用的半开半闭,最后一个是越界的.
默认是从小大到大排列
2 排序的对象一定要支持小于符号,不支持就自己写一个operatro<函数
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
class Person
{
string name;
int age;
public:
Person(const char * name,int age):name(name),age(age){}
friend ostream& operator<<(ostream&o,const Person& p)
{
return o << p.name << ' ' << p.age;
}
//标准模板库里面一般是用< 符号, 且写成const函数
//不加const 报错 passing ‘const Person’ as ‘this’ argument of ‘const bool Person::operator<(const Person&)’ discards qualifiers
const bool operator<(const Person & p) const //
{
if(name < p.name || (name == p.name && age < p.age ))
return true;
else
return false;
}
};
template <typename T>
void print(T b,T e)
{
while(b != e)
{
cout << *b++ << ' ';
}
cout << endl;
}
int main()
{
int a[6] = {8,1,6,2,3,5};
double b[4] = {5.5,3.3,6.6,2.2};
string c[5] = {"nice","to","meet","you","all"};
Person d[3] ={Person("芙蓉",18),Person("杨强",20),Person("薇薇",16)};
sort(a,a+6); //一律使用半开半闭的形式 最后一个是不用 的
sort(b,b+4);
sort(c,c+5);
sort(d,d+3);
print(a,a+6); //一律使用半开半闭的形式 最后一个是不用 的
print(b,b+4);
print(c,c+5);
print(d,d+3);
}