算法简介
函数原型:
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
#include<functional>
//sort——排序算法
void Print(int val)
{
cout << val << " ";
}
void test01()
{
vector<int>v;
v.push_back(10);
v.push_back(50);
v.push_back(20);
v.push_back(40);
v.push_back(30);
//sort升序排序
sort(v.begin(), v.end());
for_each(v.begin(), v.end(), Print);
cout << endl;
//sort降序排序
sort(v.begin(), v.end(), greater<int>());
for_each(v.begin(), v.end(), Print);
cout << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
函数原型:
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
#include<ctime>
//random_shuffle——排序算法
void Print(int val)
{
cout << val << " ";
}
void test01()
{
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(), Print);
cout << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
注:random_shuffle洗牌算法使用时需要加随机数种子?
函数原型:
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
//merge——排序算法
void Print(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 + 3);
}
//目标容器
vector<int>vTarget;
//提前给目标容器分配空间
vTarget.resize(v1.size() + v2.size());
merge(v1.begin(), v1.end(), v2.begin(), v2.end(), vTarget.begin());
for_each(vTarget.begin(), vTarget.end(), Print);
cout << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
?注:merge合并两个容器必须是有序序列
函数原型:
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
//reverse——排序算法
void Print(int val)
{
cout << val << " ";
}
void test01()
{
vector<int>v;
v.push_back(10);
v.push_back(50);
v.push_back(30);
v.push_back(40);
v.push_back(20);
cout << "反转前:" << endl;
for_each(v.begin(), v.end(), Print);
cout << endl;
cout << "反转后:" << endl;
reverse(v.begin(), v.end());
for_each(v.begin(), v.end(), Print);
cout << endl;
}
int main()
{
test01();
system("pause");
return 0;
}