#include<iostream>
#include<string>
#include<vector>
using namespace std;
#include<algorithm>
#include<functional>
#include<ctime>
//sort
void myPrint(int val)
{
cout << val << " ";
}
void test01()
{
vector<int>v;
v.push_back(10);
v.push_back(20);
v.push_back(30);
v.push_back(40);
v.push_back(50);
//利用sort升序
sort(v.begin(), v.end());
for_each(v.begin(), v.end(), myPrint);
cout << endl;
//改为降序
sort(v.begin(), v.end(), greater<int>());
for_each(v.begin(), v.end(), myPrint);
}
//洗牌算法
void test02()
{
srand((unsigned int)time(NULL));
vector<int>v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
//利用洗牌算法打乱顺序
random_shuffle(v.begin(), v.end());
for_each(v.begin(), v.end(), myPrint);
cout << endl;
}
//merge
void test03()
{
vector<int>v1;
vector<int>v2;
for (int i = 0; i < 10; i++)
{
v1.push_back(i);
v2.push_back(i + 1);
}
//目标容器 需要提前开辟空间
vector<int>v;
v.resize(v1.size() + v2.size());
//合并 需要两个有序序列
merge(v1.begin(), v1.end(), v2.begin(), v2.end(), v.begin());
for_each(v.begin(), v.end(), myPrint);
cout << endl;
}
//reverse 反转
void test04()
{
vector<int>v;
v.push_back(10);
v.push_back(20);
v.push_back(30);
v.push_back(40);
v.push_back(50);
cout << "反转前:" << endl;
for_each(v.begin(), v.end(), myPrint);
cout << endl;
reverse(v.begin(), v.end());
cout << "反转后:" << endl;
for_each(v.begin(), v.end(), myPrint);
cout << endl;
}
int main()
{
test04();
}
常用排序算法
最新推荐文章于 2023-06-30 19:45:37 发布