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;
}
相关推荐
不想写代码的星星19 小时前
std::function 详解:用法、原理与现代 C++ 最佳实践
c++
NineData2 天前
数据库管理工具NineData,一年进化成为数万+开发者的首选数据库工具?
运维·数据结构·数据库
樱木Plus3 天前
深拷贝(Deep Copy)和浅拷贝(Shallow Copy)
c++
程序员爱钓鱼3 天前
Go 操作 Windows COM 自动化实战:深入解析 go-ole
后端·go·排序算法
blasit5 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_6 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星6 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛8 天前
delete又未完全delete
c++
是希燃亚8 天前
📚 十大经典排序算法 C语言笔记(一看就会版)
排序算法
端平入洛9 天前
auto有时不auto
c++