sort算法函数排序示例

#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;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值