#include<iostream>
#include<algorithm>
#include<vector>
#include<functional>
#include<ctime>
using namespace std;
//sort排序
class nSort
{
public:
bool operator()(int num1, int num2)
{
return num1 > num2;
}
};
void test01()
{
vector<int>v = { 5,6,4,9,1,3,7,8,0,2 };
//默认升序
sort(v.begin(), v.end());
for (auto i : v)
{
cout << i << " ";
}
cout << endl;
//使用自定谓词进行降序,也可以使用关系仿函数
//sort(v.begin(), v.end(), greater<int>());
sort(v.begin(), v.end(), nSort());
for (auto i : v)
{
cout << i << " ";
}
cout << endl;
//排序类对象时需传入两个类对象
}
//random_shuffle 洗牌 指定范围内元素随机调整次序
void test02()
{
vector<int>v = { 0,1,2,3,4,5,6,7,8,9 };
//设置随机数种子
srand(time(NULL));
random_shuffle(v.begin(), v.end());
for (auto i : v)
{
cout << i << " ";
}
cout << endl;
}
//merge 两个容器元素合并(必须是有序和同序),并存储到另一个容器中,合并后还是有序
void test03()
{
vector<int>v1 = { 0,1,2,3,4,5,6,7,8,9 };
vector<int>v2 = { 1,2,3,4,5,6,7,8,9,10 };
vector<int>v3;
//设置大小
v3.resize(v1.size() + v2.size());
//合并
merge(v1.begin(), v1.end(), v2.begin(), v2.end(), v3.begin());
for (auto i : v3)
{
cout << i << " ";
}
cout << endl;
}
//reverse 反转指定范围元素
void vPrint(int v)
{
cout << v << " ";
}
void test04()
{
vector<int>v = { 0,1,2,3,4,5,6,7,8,9 };
cout << "反转前:" << endl;
//遍历
for_each(v.begin(), v.end(), vPrint);
cout << endl;
cout << "反转后:" << endl;
reverse(v.begin(), v.end());
for_each(v.begin(), v.end(), vPrint);
cout << endl;
}
int main()
{
test04();
system("pause");
return 0;
}
C++:STL-常用排序算法
最新推荐文章于 2022-10-23 20:55:06 发布