sort函数用于对序列进行排序
sort原型:
//第一种,两个参数
void sort (RandomAccessIterator first, RandomAccessIterator last);
//第二种,三个参数
void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
第一种,两个参数的情况
这种情况一般用于int,float数组的情况
first表示序列的起始位置,last表示序列的结束位置
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int a[] = {90,65,45,34,12,9,8,7}; //定义一个序列
int b = sizeof(a)/sizeof(a[0]); //计算一共有多少的成员
cout << "b = " << b << endl; //将成员的数量显示出来
sort(a,a+b); //对序列a进行升序排序
for(int i=0;i<b;i++) //将序列从开始打印
{
cout << a[i] << endl;
}
return 0;
}
在sort(a,a+b)时需要注意,b的值为序列的所有成员个数。刚开始,笔者认为如果成员为8个,那么应该是sort(a,a+7)才对,但是发现最后一个数没有被排序。笔者估计是包含first,不包含last。
第二种,三个参数的情况
上面的情况,只能进行升序排序,这是默认的情况。如果想要降序,只能使用第三个参数(回调函数)。
#include <iostream>
#include <algorithm>
using namespace std;
bool mycompare(float a, float b) //设置回调函数,参数与sort的前两个参数对应
{
return a > b; //a>b return 1;说明不需要调换
} //a<b return 0;说明需要调换
//结果就是从大到小排列
int main()
{
float a[] = {3.2,1.2,9.6,8.5};
sort(a,a+4,mycompare);
for(int i=0;i<4;i++)
{
cout << a[i] << endl;
}
return 0;
}
有第三个参数的情况还可以用于结构体排序
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
struct fruit{ //定义一个结构体
string red;
string green;
int flag;
};
bool mycompare(fruit a, fruit b) //按照flag,从小到大排序
{
return a.flag < b.flag;
}
int main()
{
vector<fruit> s_fruit; //设置一个fruit类型的vector
fruit f1; //手动建立一个fruit类型结构体
f1.red = "apple";
f1.green = "watermelon";
f1.flag = 4;
s_fruit.push_back(f1); //放入s_fruit中
fruit f2; //同理
f2.red = "strawberry";
f2.green = "luffa";
f2.flag = 3;
s_fruit.push_back(f2);
fruit f3; //同理
f3.red = "cherry";
f3.green = "cucumber";
f3.flag = 5;
s_fruit.push_back(f3);
sort(s_fruit.begin(),s_fruit.end(),mycompare); //排序
for(int i=0;i<3;i++) //显示结果
{
cout << s_fruit[i].red << endl;
cout << s_fruit[i].green << endl;
cout << s_fruit[i].flag << endl;
cout << "----------------" << endl;
}
return 0;
}
在比较的时候,要注意比较的字符类型
struct fruit{
string red;
string green;
//当定义flag为字符串时
string flag;
};
bool mycompare(fruit a, fruit b)
{
//比较的时候只比较字符串中第一个字符的大小,所以会引起错误
return a.flag < b.flag;
}
一般会将字符串转换为整形或长整型
bool mycompare(fruit a, fruit b)
{
return atol(a.flag.c_str()) < atol(b.flag.c_str());
}