STL 中有copy 函數, 感覺的效率還可以提高些, 就試著使用模板推導的方式決定調用不同的函數,本事就是根據形參類型的不同而調用不同的函數 , 首先自定義最簡單的2個類 , true_type 和 false_type , 詳見如下代碼, VS2008驗證 OK
// algorithm.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <vector> #include <list> namespace algor{ struct true_type{}; struct false_type{}; template <typename T>struct iterator_trait{ typedef false_type value_type; }; template <>struct iterator_trait<int*>{ typedef true_type value_type; }; template <>struct iterator_trait<char*>{ typedef true_type value_type; }; template <typename Iter1, typename Iter2>inline Iter2 t_copy(Iter1 first, Iter1 end, Iter2 out){ typedef iterator_trait<Iter1>::value_type value_type; return copy_impl(first, end, out, has_trivial_assign<value_type>::value_type()); } template <typename T>struct has_trivial_assign{ typedef T value_type; }; template <typename T>T* copy_impl(T* first, T* end, T* out, true_type){ memmove(out, first, (end-first)*sizeof(T)); return out + (end - first); } template <typename Iter1, typename Iter2>Iter2 copy_impl(Iter1 first, Iter1 end, Iter2 out, false_type){ while(first != end) { *out = *first; ++first; ++out; } return out; } } #define N 100000 struct MyFoo{ char c; MyFoo& operator=(const MyFoo& f){ c = f.c; return *this; } }; using namespace std; using namespace algor; int _tmain(int argc, _TCHAR* argv[]) { MyFoo f; vector<MyFoo> vect(N, f); vector<MyFoo>::iterator first = vect.begin(); vector<MyFoo>::iterator end = vect.end(); list<MyFoo> t_list; t_list.resize(N); list<MyFoo>::iterator out = t_list.begin(); int arr[N] = {1,}; int brr[N] = {2,}; int* aarr = arr; int* bbrr = brr; t_copy(aarr, aarr+N, bbrr); t_copy(first, end, out); return 0; }