Linux C++ 039-STL之拷贝和替换算法
本节关键字:Linux、C++、拷贝算法、替换算法
相关库函数:copy、replace、replace_if、swap
copy()
功能描述:容器内指定范围的元素拷贝到另一容器中
函数原型:
copy(iterator beg, iterator end, iterator dest);
// dest - 目标起始迭代器
示例:
#include <vector>
#include <algorithm>void myPrint(const int val)
{cout << val << " ";
}
void test01()
{vector<int> v1;for(int i=0;i<10;i++){v1.push_back(i);}vector<int> v2;v2.resize(v1.size());copy(v1.begin(), v1.end(), v2.begin());for_each(v2.begin, v2.end(), myPrint);cout << endl;
}
总结:利用copy算法在拷贝时,目标容器记得提前开辟空间
replace()
功能描述:将容器内指定范围的旧元素改为新元素
函数原型:
replace(iterator beg, iterator end, oldvalue, newvalue);
示例:
#include <vector>
#include <algorithm>class MyPrint
{
public:void operator()(const int val){cout << val << " ";}
};
void myPrint(const int val)
{cout << val << " ";
}
void test01()
{vector<int> v;for(int i=0;i<5;i++){v.push_back(1);}for_each(v.begin(), v.end(), myPrint);cout << endl;raplace(v.begin(), v.end(), 1, 2);for_each(v.begin(), v.end(), myPrint);//for_each(v.begin(), v.end(), MyPrint());cout << endl;
}
replace_if()
功能描述:将区间内满足条件的元素,替换成指定元素
函数原型:
replayce_if(iterator beg, iterator end, _Pred, newvalue);
// _Pred - 谓词
示例:
#include <vector>
#include <algorithm>class MyPrint
{
public:void operator()(const int val){cout << val << " ";}
}
class Greater3
{
public:bool operator()(const int val){return val >= 3;}
};
void myPrint(const int val)
{cout << val << " ";
}
void test01()
{vector<int> v;for(int i=0;i<5;i++){v.push_back(1);}for_each(v.begin(), v.end(), myPrint);//for_each(v.begin(), v.end(), MyPrint());cout << endl;raplace_if(v.begin(), v.end(), Greater3, 20);for_each(v.begin(), v.end(), myPrint);//for_each(v.begin(), v.end(), MyPrint());cout << endl;
}
总结:replace_if按条件替换,可以利用仿函数灵活筛选满足的条件
swap()
功能描述:互换两个容器的元素
函数原型:
swap(container c1, container c2);
// container - 交换类型
// 注意:交换的容器类型要一致
示例:
#include <vector>
#include <algorithm>class MyPrint
{
public:void operator()(const int val){cout << val << " ";}
};
void test01()
{vector<int> v1;for(int i=0;i<5;i++){v1.push_back(1);}vector<int> v2;for(int i=0;i<5;i++){v2.push_back(2);}for_each(v1.begin(), v1.end(), MyPrint());cout << endl;swap(v1, v2);for_each(v1.begin(), v1.end(), MyPrint());cout << endl;
}
总结:swap交换容器中的元素时,交换的容器类型要一致