这篇继续学习C++中的排序算法,还剩merge合并算法和reverse反转算法。合并就是把两个相同类型的容器合并到第三个容器中,这个合并是有条件的。反转就是原来是队列头部,反转后变成队列尾部。反转感觉在面试考察比较多,不管是JAVA还是C++的面试。
1.merge合并
作用:将两个容器合并到第三个容器
函数原型:merge(iteator v1.begin,iteator v1.end, iteator v2.begin, iteator v2.end, iteator v3.begin);
注意:
1.两个容器都需要有序,而且顺序一致,不能一个升序一个降序
2.第三个容器初始化设置大小等于前面两个容器大小之和
练习代码
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
void Print01(int val)
{
cout << val << " ";
};
void test01()
{
vector<int> v1;
vector<int> v2;
for(int i = 0; i < 10; i++)
{
v1.push_back(i); // 0 到9 序列
v1.push_back(i+1); //1到10 序列
}
// merge 容器合并
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(), Print01);
cout << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
测试结果:
2.reverse反转
将容器内元素进行反转
函数原型:reverse(iteator begin, iteator end);
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
void Print01(int val)
{
cout << val << " ";
};
void test01()
{
vector<int> v1;
v1.push_back(10);
v1.push_back(50);
v1.push_back(30);
v1.push_back(40);
v1.push_back(20);
cout << "before reverse" << endl;
for_each(v1.begin(), v1.end(), Print01);
cout << endl;
cout << "after reverse"<< endl ;
reverse(v1.begin(), v1.end());
for_each(v1.begin(), v1.end(), Print01);
cout << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
运行结果