本文共 1592 字,大约阅读时间需要 5 分钟。
学习目标:
算法简介:
copy
// 容器内指定范围的元素拷贝到另一容器中replace
// 将容器内指定范围的旧元素修改为新元素replace_if
// 容器内指定范围满足条件的元素替换为新元素swap
// 互换两个容器的元素功能描述:
函数原型:
copy(iterator beg, iterator end, iterator dest);
beg
是起始迭代器, end
是结束迭代器, dest
是目标容器的起始迭代器。 示例:
#include #include #include using namespace std; class myPrint {public:void operator()(int val) {cout << val << " ";}}; void test01() {vector v1 = {1, 2, 3, 4, 5};vector v2;copy(v1.begin(), v1.end(), back_inserter(v2));cout << "v2: ";myPrint p;for_each(v2.begin(), v2.end(), p);cout << endl;}
功能描述:
函数原型:
replace(iterator begin, iterator end, const T& value);
示例:
#include #include #include using namespace std; void test02() {vector v1 = {1, 2, 3, 4, 5};replace(v1.begin(), v1.end(), 10);cout << "v1: ";for (int val : v1) {cout << val << " ";}cout << endl;}
功能描述:
函数原型:
replace_if(iterator begin, iterator end, Pred pred, const T& value);
示例:
#include #include #include #include using namespace std; void test03() {vector v1 = {1, 2, 3, 4, 5};replace_if(v1.begin(), v1.end(), not_less(5), 10);cout << "v1: ";for (int val : v1) {cout << val << " ";}cout << endl;}
功能描述:
函数原型:
swap(iterator& begin, iterator& end, Container& other);
示例:
#include #include #include using namespace std; void test04() {vector v1 = {1, 2, 3};vector v2 = {4, 5, 6};swap(v1.begin(), v1.end(), v2.begin(), v2.end());cout << "v1: ";for (int val : v1) {cout << val << " ";}cout << "v2: ";for (int val : v2) {cout << val << " ";}cout << endl;}
转载地址:http://esxv.baihongyu.com/