一、算法简介
1、sort //对容器内元素进行排序
2、random_shuffle //洗牌 指定范围内的元素随机调整次序
3、merge //容器元素合并,并存储到另一容器中
4、reverse //反转指定范围的元素
二、sort
1、函数原型
sort(iterator beg,iterator end,_Pred); //_Pred谓词
2、示例
代码如下(示例):
#include<iostream>
#include<vector>
#include<algorithm>
#include<functional>
using namespace std;
void MyPrint(int val)
{
cout << val << " ";
}
void test01()
{
vector<int>v;
v.push_back(30);
v.push_back(50);
v.push_back(20);
v.push_back(40);
v.push_back(10);
//用sort做升序处理
sort(v.begin(), v.end());
for_each(v.begin(), v.end(), MyPrint);
cout << endl;
sort(v.begin(), v.end(), greater<int>());
cout << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
三、random_shuffle
1、函数原型
random_shuffle(iterator beg,iterator end); //指定范围内的元素随机调整次序
2、示例
代码如下(示例):
#include<iostream>
#include<vector>
#include<algorithm>
#include<functional>
using namespace std;
void MyPrint(int val)
{
cout << val << " ";
}
void test01()
{
vector<int>v;
v.push_back(30);
v.push_back(50);
v.push_back(20);
v.push_back(40);
v.push_back(10);
//用sort做升序处理
sort(v.begin(), v.end());
for_each(v.begin(), v.end(), MyPrint);
cout << endl;
sort(v.begin(), v.end(), greater<int>());
cout << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
四、merge
1、功能描述
两个容器元素合并,并存在另外一个容器里
2、函数原型
merge(iterator beg1,iterator end1,iterator beg2,iterator end2,iterator dest); //容器元素合并,dest目标容器开始迭代器
注意:两个容器必须是有序的
3、示例
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void myPrint(int val)
{
cout << val << " ";
}
void test01()
{
vector<int>v;
vector<int>v2;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
v2.push_back(i + 1);
}
//目标容器
vector<int>vTarget;
//提前给目标容器分配空间
vTarget.resize(v.size() + v2.size());
merge(v.begin(), v.end(), v2.begin(), v2.end(), vTarget);
for_each(vTarget.begin(), vTarget.end(),myPrint);
}
int main()
{
test01();
system("pause");
return 0;
}
五、reverse
1、函数原型
reverse(iterator beg,iterator end); //反转指定范围的元素
2、示例
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void myPrint(int val)
{
cout << val << " ";
}
void test01()
{
vector<int>v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
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);
}
int main()
{
test01();
system("pause");
return 0;
}