C++ Sort函数用法

#include <iostream>
using namespace std;
#include <vector>
#include <algorithm>

typedef struct Test
{
public:
	int n;
	char* s;
}Test;

vector<Test> t;

bool intcmp(Test a,Test b)
{    
	return a.n < b.n;
}

bool strcmp1(Test a,Test b)
{    
	return strcmp(a.s,b.s) < 0;
}

int main()
{
	Test tmp = {0};

	tmp.n = 4;
	tmp.s = "gggg";
	t.push_back(tmp);

	tmp.n = 1;
	tmp.s = "dddd";
	t.push_back(tmp);

	tmp.n = 2;
	tmp.s = "cccc";
	t.push_back(tmp);

	sort(t.begin(),t.end(),strcmp1);

	for (vector<Test>::iterator iter = t.begin(); iter != t.end(); ++iter)
	{
		cout << iter->s << endl;
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++标准库中的`std::sort`函数是用于对容器(如`std::vector`, `std::array`, 或自定义容器)中的元素进行排序的成员函数。它使用快速排序算法(通常有优化版本),对元素进行升序排列。`sort`函数的基本用法如下: ```cpp template <class RandomIt> void sort(RandomIt first, RandomIt last); ``` 这里的`first`参数是要排序的范围的第一个元素的迭代器,`last`参数是排序范围的结束位置(不包含该元素)。 如果容器中的元素是非可比较的,或者需要自定义排序规则,可以提供一个比较函数或三元操作符作为第二个参数: ```cpp template <class RandomIt, class Compare> void sort(RandomIt first, RandomIt last, Compare comp); ``` 或者 ```cpp template <class RandomIt> void sort(RandomIt first, RandomIt last, bool (*pred)(RandomIt, RandomIt)); ``` 其中,`Compare`是一个对象,或者是满足`bool Compare(const T& a, const T& b)`签名的函数指针,用来指定元素间的比较规则;`pred`是一个返回`bool`值的函数指针,接受两个迭代器作为参数,表示它们所指向的元素之间的关系。 例子: ```cpp std::vector<int> v = {5, 2, 9, 1, 5, 6}; std::sort(v.begin(), v.end()); // 对vector进行默认升序排序 // 自定义排序 std::sort(v.begin(), v.end(), std::greater<int>()); // 降序排序 // 使用比较函数 bool compare(const int& a, const int& b) { return a > b; } std::sort(v.begin(), v.end(), compare); // 按照自定义规则排序 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值