C++primer习题4.6数组复制

用模板写一个:

#include <string>
#include <iostream>
#include<vector>
using namespace std;
template<class T>
T* copy(T *a,int size)
{
   T* b = new T[size];
   for (int i = 0; i < size; ++i)
   {
	   b[i] = a[i];
   }
   return b;
}
int main()
{
	int a[] = {1,2,3,4};
	int size = sizeof(a)/sizeof(*a);
	int *b = copy(a,size);
	for (int i = 0; i < size; ++i)
	{
		cout << b[i] << " ";
	}
}

换成vector:

#include <string>
#include <iostream>
#include<vector>
using namespace std;
template<class T>
vector<T> copy(vector<T> a)
{
   vector<T> b;
   for (size_t i = 0; i != a.size(); ++i)
   {
	   b.push_back(a[i]);
   }
   return b;
}

int main()
{
	vector<int> a(10,1);
	vector<int> b = copy(a);
	for (vector<int>::iterator iter = b.begin(); iter != b.end(); ++iter)
	{
		cout << *iter << " ";
	}
}

posted @ 2011-06-10 19:47  hailong  阅读(339)  评论(0编辑  收藏  举报