class Greater
{
public:
bool operator()(int val1,int val2)
{
return val1 > val2;
}
};
class Pr
{
public:
void operator()(int val)
{
cout << val << " " ;
}
};
void test01()
{
vector<int>v1;
v1.push_back(2);
v1.push_back(1);
v1.push_back(4);
v1.push_back(2);
sort(v1.begin(), v1.end(),Greater());//降序
//sort(v1.begin(), v1.end(), greater<int>());//降序
for_each(v1.begin(), v1.end(), Pr());
cout << endl;
}
class Pr
{
public:
void operator()(int val)
{
cout << val << " " ;
}
};
void test01()
{
vector<int>v1;
v1.push_back(1);
v1.push_back(2);
v1.push_back(3);
v1.push_back(4);
random_shuffle(v1.begin(), v1.end());
for_each(v1.begin(), v1.end(), Pr());
cout << endl;//1 2 4 3 不加随机种子时每次顺序都一样
}
class Pr
{
public:
void operator()(int val)
{
cout << val << " " ;
}
};
void test01()
{
vector<int>v1;
v1.push_back(1);
v1.push_back(2);
v1.push_back(3);
v1.push_back(4);
vector<int>v2;
v2.push_back(5);
v2.push_back(6);
v2.push_back(7);
v2.push_back(8);
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(), Pr());
cout << endl;//1 2 3 4 5 6 7 8
}
注意:v1和v2的升降顺序也要相同
class Pr
{
public:
void operator()(int val)
{
cout << val << " " ;
}
};
void test01()
{
vector<int>v1;
v1.push_back(1);
v1.push_back(2);
v1.push_back(3);
v1.push_back(4);
cout << "反转前" << endl;
for_each(v1.begin(), v1.end(), Pr());
cout << endl;//1 2 3 4
cout << "反转后" << endl;
reverse(v1.begin(), v1.end());
for_each(v1.begin(), v1.end(), Pr());
cout << endl;//4 3 2 1
}