算法简介:
copy
//容器内指定范围的元素拷贝到另一容器中replace
//将容器内指定范围的旧元素修改为新元素replace_if
//容器内指定范围满足条件的元素替换为新元素swap
//互换两个容器的元素功能描述:
函数原型:
copy(iterator beg, iterator end, iterator dest);
#include
#include
#include
using namespace std;
template<class T>
void myPrint(T val)
{
cout << val << '\t';
}
void test1()
{
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<int>);
cout << endl;
}
int main()
{
test1();
}
功能描述:
函数原型:
#include
#include
#include
using namespace std;
template<class T>
class MyPrint
{
public:
void operator()(T val)
{
cout << val << '\t';
}
};
void test1()
{
vector<int>v;
v.push_back(20);
v.push_back(30);
v.push_back(50);
v.push_back(30);
v.push_back(40);
v.push_back(20);
v.push_back(10);
v.push_back(20);
cout << "替换前:" << endl;
for_each(v.begin(), v.end(), MyPrint<int>());
cout << endl;
cout << "替换后" << endl;
replace(v.begin(), v.end(), 20, 2000);
for_each(v.begin(), v.end(), MyPrint<int>());
cout << endl;
}
int main()
{
test1();
}
功能描述:
函数原型:
replace_if(iterator beg, iterator end, _pred, newvalue);
#include
#include
#include
using namespace std;
template<class T>
class MyPrint
{
public:
void operator()(T val)
{
cout << val << '\t';
}
};
class Greater30
{
public:
bool operator()(int val)
{
return val >= 30;
}
};
void test1()
{
vector<int>v;
v.push_back(10);
v.push_back(40);
v.push_back(20);
v.push_back(40);
v.push_back(30);
v.push_back(50);
v.push_back(20);
v.push_back(30);
cout << "替换前:" << endl;
for_each(v.begin(), v.end(), MyPrint<int>());
cout << endl;
cout << "替换后" << endl;
replace_if(v.begin(), v.end(), Greater30(), 3000);
for_each(v.begin(), v.end(), MyPrint<int>());
cout << endl;
}
int main()
{
test1();
}
功能描述:
函数原型:
swap(container c1, container c2);
#include
#include
#include
using namespace std;
template<class T>
class MyPrint
{
public:
void operator()(T val)
{
cout << val << '\t';
}
};
class Greater30
{
public:
bool operator()(int val)
{
return val >= 30;
}
};
void test1()
{
vector<int>v1;
vector<int>v2;
for (int i = 0; i < 10; i++)
{
v1.push_back(i);
v2.push_back(i + 100);
}
cout << "交换前:" << endl;
for_each(v1.begin(), v1.end(), MyPrint<int>());
cout << endl;
for_each(v2.begin(), v2.end(), MyPrint<int>());
cout << endl;
cout << "---------------------------------------------------------------------" << endl;
cout << "交换后" << endl;
swap(v1, v2);
for_each(v1.begin(), v1.end(), MyPrint<int>());
cout << endl;
for_each(v2.begin(), v2.end(), MyPrint<int>());
cout << endl;
}
int main()
{
test1();
}