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;
}
相关推荐
Darling噜啦啦2 天前
列表转树算法深度解析:从 Map 到 Reduce 的两种实现,面试高频考点
数据结构·算法·面试
clint4562 天前
C++进阶(1)——前景提要
c++
夜悊2 天前
C++代码示例:进制数简单生成工具
c++
郝学胜_神的一滴2 天前
CMake 021: IF 条件判据详诠
c++·cmake
_wyt0013 天前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp
小小工匠3 天前
Redis - 事务机制:能实现 ACID 属性吗
数据结构·redis·性能优化·并发·持久化
玖玥拾3 天前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
один but you3 天前
constexpr函数
c++
Qres8213 天前
算法复键——树状数组
数据结构·算法
凡人叶枫3 天前
Effective C++ 条款41:了解隐式接口和编译期多态
java·开发语言·c++·effective c++