STL——常用排序算法

1.sort()

cpp 复制代码
void MyPrint(int val)
{
	cout << val << " ";
}
void test01()
{
	vector<int> v1;
	v1.push_back(10);
	v1.push_back(20);
	v1.push_back(40);
	v1.push_back(30);
	v1.push_back(20);
	v1.push_back(40);
	v1.push_back(50);
	sort(v1.begin(), v1.end(), greater<int>());//用内建函数模板实现降序
	for_each(v1.begin(), v1.end(), MyPrint);
	cout << endl;
}

2.random_shuffle()//随机打乱顺序

cpp 复制代码
void MyPrint(int val)
{
	cout << val << " ";
}
void test01()
{
	vector<int> v1;
	srand((unsigned int)time(NULL));//随机数种子
	for (int i = 0; i < 10; i++)
	{
		v1.push_back(i);
	}
	for_each(v1.begin(), v1.end(), MyPrint);
	cout << endl;
	cout << "随机打乱顺序后" << endl;
	random_shuffle(v1.begin(), v1.end());//随机打乱顺序
	for_each(v1.begin(), v1.end(), MyPrint);
	cout << endl;
}

3.merge()//归并

cpp 复制代码
void MyPrint(int val)
{
	cout << val << " ";
}
void test01()
{
	vector<int> v1;
	vector<int> v2;
	for (int i = 0; i < 10; i++)
	{
		v1.push_back(i);
		v2.push_back(i + 1);
	}
	vector<int> v3;
	v3.resize(v1.size() + v2.size());//归并前必须先开辟空间
	merge(v1.begin(), v1.end(), v2.begin(), v2.end(), v3.begin());//必须是有序且升序
	for_each(v3.begin(), v3.end(), MyPrint);
	cout << endl;
}

4.reverse()//反转

cpp 复制代码
void MyPrint(int val)
{
	cout << val << " ";
}
void test01()
{
	vector<int> v1;
	for (int i = 0; i < 10; i++)
	{
		v1.push_back(i);
	}
	cout << "反转前:" << endl;
	for_each(v1.begin(), v1.end(), MyPrint);
	cout << endl;
	reverse(v1.begin(), v1.end());//实现反转
	cout << "反转后:" << endl;
	for_each(v1.begin(), v1.end(), MyPrint);
	cout << endl;
}
相关推荐
老洋葱Mr_Onion3 分钟前
【C++】高精度模板
开发语言·c++·算法
我不是懒洋洋1 小时前
从零实现一个分布式计算:MapReduce的核心设计
c++
白白白小纯10 小时前
算法篇—反转链表
c语言·数据结构·算法·leetcode
小王C语言11 小时前
【7. 实现登录注册模块】:实现会话管理、注册/登录/退出 API
网络·c++
峥无14 小时前
C++11 深度详解:现代 C++ 基石全梳理
开发语言·c++·笔记
阿米亚波14 小时前
【C++ STL】std::unordered_multimap
开发语言·数据结构·c++·笔记·stl
小王C语言14 小时前
【3. 基于 Vibe Coding 的 OJ 平台】. 构建仓库、环境准备、需求梳理、安装依赖
网络·c++
小王C语言15 小时前
【8.进行接口测试】:通过 curl 进行接口自动化测试 / 通过 python 程序进行接口自动化测试
网络·c++
三克的油16 小时前
数据结构-4
数据结构
888CC++16 小时前
C++ 快速学习指南:从入门到进阶的实战路线
开发语言·c++