C++primer練習問題4.6配列コピー

1221 ワード

テンプレートで次のように書きます.
#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 << " ";
	}
}