C++ vector容器遍历,复制

32 篇文章 0 订阅
#include<iostream>
#include<vector>
#include<functional>
#include<algorithm>
using namespace std;

void myPrint01(int v1) {
	cout << v1 << " ";
}

class myPrint02 {
public:
	void operator()(int v1)
	{	
		cout << v1 << " ";
		this->p_cout++;
	}
	int p_cout = 0;
};

class myPrint03:public binary_function<int,int,void> {
public:
	void operator()(int v1,int start)const
	{
		cout << v1+start <<" ";
	}
};

void test01() {
	vector<int> v1;
	v1.push_back(10);
	v1.push_back(20);
	v1.push_back(30);
	v1.push_back(40);
	v1.push_back(50);

	for_each(v1.begin(), v1.end(), myPrint01);
	cout << endl;

	myPrint02 p2 = for_each(v1.begin(), v1.end(), myPrint02());
	cout << " p2:" << p2.p_cout << endl;

	for_each(v1.begin(), v1.end(), bind2nd(myPrint03(),1000));
	cout << endl;

	for_each(v1.begin(), v1.end(), [](int val) { cout << val << " "; });
	cout << endl;

	for (vector<int>::iterator i = v1.begin(); i != v1.end(); ++i) {
		cout << *i << " ";
	}
	cout << endl;
}

class MyTransform
{
public:
	int operator()(int val)
	{
		return val;
	}
};

//元素搬运
void test02() {
	vector<int> v2;
	for (int i = 1; i <= 10; i++) {
		v2.push_back(i * 10);
	}

	vector<int> v;
	v.resize(v2.size());

	transform(v2.begin(), v2.end(), v.begin(), MyTransform());

	for_each(v.begin(), v.end(), [](int val) {cout << val << " "; });
	cout << endl;
}

int main() {
	test01();
	cout << "-------------------------" << endl;
	test02();
	system("pause");
	return EXIT_SUCCESS;
}
10 20 30 40 50
10 20 30 40 50  p2:5
1010 1020 1030 1040 1050
10 20 30 40 50
10 20 30 40 50
-------------------------
10 20 30 40 50 60 70 80 90 100
请按任意键继续. . .

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值