merge、sort、random_shuffle、reverse
#include<iostream>
#include<vector>
#include<algorithm>
#include<functional>
#include<ctime>
using namespace std;
class myCompareClass {
public:
bool operator()(int v1,int v2)const
{
return v1 > v2;
}
};
bool myCompareFunction(int v1,int v2) {
return v1 < v2;
}
//merge合并两个容器
void test01() {
vector<int> v1;
vector<int> v2;
for (int i = 1; i <= 10; i++) {
v1.push_back(i);
v2.push_back(i * 2);
}
vector<int> target;
target.resize(v1.size()+v2.size());
//v1,v2必须有序
merge(v1.begin(), v1.end(), v2.begin(), v2.end(), target.begin());
for_each(target.begin(), target.end(), [](int val) {cout << val << " "; });
cout << endl;
}
//sort排序
void test02() {
vector<int>v2;
for (int i = 1; i <= 10; i++)
{
v2.push_back(i);
}
sort(v2.begin(),v2.end(),greater<int>());
for_each(v2.begin(), v2.end(), [](int val) {cout << val << " "; });
cout << endl;
sort(v2.begin(),v2.end(),myCompareFunction);
for_each(v2.begin(), v2.end(), [](int val) {cout << val << " "; });
cout << endl;
sort(v2.begin(), v2.end(), myCompareClass());
for_each(v2.begin(), v2.end(), [](int val) {cout << val << " "; });
cout << endl;
}
//random_shuffle对指定范围内的元素随机调整次序
void test03() {
vector<int>v3;
for (int i = 1; i <= 10; i++)
{
v3.push_back(i);
}
random_shuffle(v3.begin(), v3.end());
for_each(v3.begin(), v3.end(), [](int val) {cout << val << " "; });
cout << endl;
}
//reverse反转指定范围的元素
void test04() {
vector<int>v4;
for (int i = 1; i <= 10; i++)
{
v4.push_back(i);
}
cout << "反转前:";
for_each(v4.begin(), v4.end(), [](int val) {cout << val << " "; });
cout << endl;
reverse(v4.begin(), v4.end());
cout << "反转后:" ;
for_each(v4.begin(), v4.end(), [](int val) {cout << val << " "; });
cout << endl;
}
int main() {
test01();
cout << "----------------------------" << endl;
test02();
cout << "----------------------------" << endl;
test03();
cout << "----------------------------" << endl;
test04();
system("pause");
return EXIT_SUCCESS;
}
1 2 2 3 4 4 5 6 6 7 8 8 9 10 10 12 14 16 18 20
----------------------------
10 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 10
10 9 8 7 6 5 4 3 2 1
----------------------------
9 2 10 3 1 6 8 4 5 7
----------------------------
反转前:1 2 3 4 5 6 7 8 9 10
反转后:10 9 8 7 6 5 4 3 2 1
请按任意键继续. . .