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;
}
相关推荐
见叶之秋2 分钟前
【C++】红与黑的边界:红黑树从插入到自检
数据结构·c++·算法·面试
程序猿编码25 分钟前
不依赖 vLLM/llama.cpp:一套面向学习的 DeepSeek-R1 CUDA 推理实现
c++·学习·语言模型·llama·vllm·大模型推理
kiracrimson43 分钟前
string 容器:从 C 字符串到会自己扩容的类
开发语言·数据结构·c++·stl
程序猿编码1 小时前
纯 C++ 手写 LLM 推理引擎:分页 KV 缓存、连续批、多卡张量并行全部内置
c++·深度学习·缓存·大模型推理·自动微分·模型推理
G018_star sky♬1 小时前
nodeJS他是如何用JavaScript封装C++的呢
开发语言·javascript·c++
choumin2 小时前
C++中std::move和std::forward的关系和区别
c++·std move·std forward·关系和区别
程序猿编码2 小时前
YOLOv5/v7/YOLOX 全支持:基于 TensorRT 的工业视觉推理底座详解
c++·yolo·机器学习·推理·模型推理
CQU_JIAKE2 小时前
10.25【A】
数据结构·算法
kyle~2 小时前
C++ 原子操作、内存模型与无锁并发编程
linux·开发语言·c++·操作系统
another heaven2 小时前
【C/C++ C++ 面向对象架构的五大特点与能力场景:封装、继承、多态、抽象与 RAII(含实战案例)】
c语言·c++·架构