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;
}
相关推荐
im_AMBER9 小时前
Leetcode 115 分割链表 | 随机链表的复制
数据结构·学习·算法·leetcode
数智工坊9 小时前
【数据结构-树与二叉树】4.7 哈夫曼树
数据结构
!!!!8139 小时前
蓝桥备赛Day1
数据结构·算法
Mr_Xuhhh9 小时前
介绍一下ref
开发语言·c++·算法
七点半7709 小时前
linux应用编程部分
数据结构
王老师青少年编程9 小时前
2024年信奥赛C++提高组csp-s初赛真题及答案解析(完善程序第2题)
c++·题解·真题·初赛·信奥赛·csp-s·提高组
静听山水9 小时前
Redis核心数据结构-Hash
数据结构·redis·哈希算法
Trouvaille ~9 小时前
【Linux】进程间关系与守护进程详解:从进程组到作业控制到守护进程实现
linux·c++·操作系统·守护进程·作业·会话·进程组
Mr_Xuhhh9 小时前
C++11实现线程池
开发语言·c++·算法
zhim009 小时前
数据结构笔记(上)(看这亿点就够了)
数据结构