sort(iterator beg, iterator end, _Pred);
//对容器内元素进行排序
random_shuffle(iterator beg, iterator end);
// 指定范围内的元素随机调整次序
//使用时记得加随机数种子
merge(iterator beg1, iterator end1, iterator beg2, iterator end2, iterator dest);
// 容器元素合并,并存储到另一容器中
// 注意: 两个容器必须是有序的
reverse(iterator beg, iterator end);
// 反转指定范围的元素
void print(int val)
{
cout << val << " ";
}
bool cmp(int v1, int v2)
{
return v1%10 > v2%10;
}
int main()
{
srand((unsigned int) time (NULL));
vector<int> v1;
vector<int> v2;
v1.push_back(23);v1.push_back(3);v1.push_back(43);v1.push_back(9);v1.push_back(61);
v1.push_back(62);v1.push_back(2);v1.push_back(9);v1.push_back(6);
v2.push_back(45);v2.push_back(57);v2.push_back(3);v2.push_back(23);
sort(v1.begin(), v1.end());//!!
for_each(v1.begin(), v1.end(), print);//2 3 6 9 9 23 43 61 62
sort(v2.begin(), v2.end());//!!
cout << endl;
for_each(v2.begin(), v2.end(), print);//3 23 45 57
cout << endl;
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(), print);//2 3 3 6 9 9 23 23 43 45 57 61 62
reverse(v3.begin(), v3.end());
cout << endl;
for_each(v3.begin(), v3.end(), print);//62 61 57 45 43 23 23 9 9 6 3 3 2
random_shuffle(v3.begin(), v3.end());
cout << endl;
for_each(v3.begin(), v3.end(), print);//6 57 3 43 9 23 62 2 3 61 23 45 9
sort(v3.begin(), v3.end(), cmp);
cout << endl;
for_each(v3.begin(), v3.end(), print);//9 9 57 6 45 43 3 23 3 23 62 2 61
return 0;
}
copy(iterator beg, iterator end, iterator dest);
// 容器内指定范围的元素拷贝到另一容器中
//利用copy算法在拷贝时,目标容器记得提前开辟空间
//如果是完全拷贝,建议直接用拷贝构造函数的形式,简易的同时也不用提前开辟空间
replace(iterator beg, iterator end, oldvalue, newvalue);
// 将区间内旧元素 替换成 新元素
replace_if(iterator beg, iterator end, _pred, newvalue);
// 按条件替换元素,满足条件的替换成指定元素
swap(container c1, container c2);
// 互换两个容器的元素
swap交换容器时,注意交换的容器要同种类型
void print(int val)
{
cout << val << " ";
}
bool great10(int val)
{
return val >= 10;
}
int main()
{
vector<int> v1;
vector<int> v2;
v1.push_back(5);v1.push_back(3);v1.push_back(45);v1.push_back(5);v1.push_back(61);
v1.push_back(62);v1.push_back(2);v1.push_back(5);v1.push_back(6);
v2.push_back(45);v2.push_back(57);v2.push_back(3);v2.push_back(23);
for_each(v1.begin(), v1.end(), print);//5 3 45 5 61 62 2 5 6
cout << endl;
replace(v1.begin(), v1.end(), 5, 500);
for_each(v1.begin(), v1.end(), print);//500 3 45 500 61 62 2 500 6
cout << endl;
replace_if(v1.begin(), v1.end(), great10, 100);
for_each(v1.begin(), v1.end(), print);//100 3 100 100 100 100 2 100 6
cout << endl;
for_each(v2.begin(), v2.end(), print);//45 57 3 23
cout << endl;
swap(v1, v2);
for_each(v2.begin(), v2.end(), print);//100 3 100 100 100 100 2 100 6
cout << endl;
vector<int> v3;
//v3.resize(v2.size());
v3 = v2;//用拷贝构造不需要提前开辟空间
//copy(v2.begin(), v2.end(), v3.begin());
for_each(v3.begin(), v3.end(), print);//100 3 100 100 100 100 2 100 6
cout << endl;
return 0;
}
转载:https://blog.csdn.net/akyna/article/details/113820527
查看评论