C++ vector容器元素替换、拷贝
#include<iostream>#include<string>#include<vector>#include<algorithm>#include<functional>#include<iterator>using namespace std;//copy 将容器内指定范围的元素拷贝到另一容器中void test01
·
copy、replace、replace_if、swap
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<functional>
#include<iterator>
using namespace std;
//copy 将容器内指定范围的元素拷贝到另一容器中
void test01() {
vector<int>v1;
for (int i = 0; i < 10; i++)
{
v1.push_back(i);
}
vector<int> target;
target.resize(v1.size());
copy(v1.begin(),v1.end(),target.begin());
for_each(target.begin(), target.end(), [](int val) {cout << val << " "; });
cout << endl;
copy(target.begin(), target.end(), ostream_iterator<int>(cout, " "));
cout << endl;
}
class myReplace {
public:
bool operator()(int v1) const
{
return v1 > 5;
}
};
//replace将容器内指定范围的旧元素修改为新元素
//replace_if(iterator beg, iterator end, _callback, newvalue)按条件替换
void test02() {
vector<int> v2;
for (int i = 1; i <= 10; i++)
{
v2.push_back(i);
}
replace(v2.begin(),v2.end(),5,500);
for_each(v2.begin(), v2.end(), [](int val) {cout << val << " "; });
cout << endl;
replace_if(v2.begin(),v2.end(),myReplace(),123);
copy(v2.begin(), v2.end(), ostream_iterator<int>(cout, " "));
cout << endl;
}
//swap交换
void test03() {
vector<int>v3;
for (int i = 1; i <= 10; i++)
{
v3.push_back(i);
}
vector<int>v4(10, 1);
copy(v3.begin(), v3.end(), ostream_iterator<int>(cout, " "));
cout << endl;
copy(v4.begin(), v4.end(), ostream_iterator<int>(cout, " "));
cout << endl;
swap(v3,v4);
copy(v3.begin(), v3.end(), ostream_iterator<int>(cout, " "));
cout << endl;
copy(v4.begin(), v4.end(), ostream_iterator<int>(cout, " "));
cout << endl;
}
int main() {
test01();
cout << "--------------------------" << endl;
test02();
cout << "--------------------------" << endl;
test03();
system("pause");
return EXIT_SUCCESS;
}
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
--------------------------
1 2 3 4 500 6 7 8 9 10
1 2 3 4 123 123 123 123 123 123
--------------------------
1 2 3 4 5 6 7 8 9 10
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 2 3 4 5 6 7 8 9 10
请按任意键继续. . .
accumulate、fill
#include<iostream>
#include<vector>
#include<numeric>
#include<algorithm>
#include<iterator>
using namespace std;
//accumulate算法 计算容器元素累计总和
void test01() {
vector<int>v1;
for (int i = 1; i <= 100; i++)
{
v1.push_back(i);
}
int res = accumulate(v1.begin(), v1.end(), 1000);//初始值1000
cout << "result: " << res << endl;
}
//fill算法 向容器中添加元素
void test02() {
vector<int>v2;
v2.resize(10);
fill(v2.begin(), v2.end(), 10);
copy(v2.begin(), v2.end(),ostream_iterator<int>(cout," "));
cout << endl;
}
int main() {
test01();
cout << "------------------------" << endl;
test02();
system("pause");
return EXIT_SUCCESS;
}
result: 6050
------------------------
10 10 10 10 10 10 10 10 10 10
请按任意键继续. . .
更多推荐
已为社区贡献2条内容
所有评论(0)