#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
// 自己定义的比较函数,sort默认按照运算符'<'的关系从小到大进行排序。
// 通过定义自己的比较函数,可以定义“自己想要的<关系",并在满足这种关系时,返回true。
// 比较函数的输入参数为待比较的对象。
bool comp(const string str1, const string str2)
{
if (str1 > str2)
{
return true;
}
return false;
}
int main()
{
// 使用sort函数来进行元素排序
// 不自己定义比较函数,对数组进行排序的情况
// sort()中首个参数为数组首元素地址,第二个参数为数组首元素+数组元素个数(这里需注意)
int arrayTest1[5] = {3, 4, 1, 2, 5};
sort(arrayTest1, arrayTest1 + 5);
for (int i = 0; i < 5; i++)
{
cout << arrayTest1[i] << endl;
}
// 不自己定义比较函数,对vector进行排序的情况
vector<int> test2;
test2.push_back(10);
test2.push_back(8);
test2.push_back(7);
test2.push_back(11);
test2.push_back(1);
sort(test2.begin(), test2.end());
for (vector<int>::iterator iter = test2.begin(); iter != test2.end(); iter++)
{
cout << *iter << endl;
}
// 自己定义比较函数,对数组或vector进行排序
vector<string> test3;
test3.push_back("dawei");
test3.push_back("huangxiaoming");
test3.push_back("zhuzhihao");
test3.push_back("woshinidie");
sort(test3.begin(), test3.begin() + test3.size(), comp);
for (vector<string>::iterator iter = test3.begin(); iter != test3.end(); iter++)
{
cout << *iter << endl;
}
return 0;
}
sort算法函数排序示例
最新推荐文章于 2022-08-21 22:48:36 发布