## C++ STL copy函数效率分析

在C++编程中，经常会配到数据的拷贝，如数组之间元素的拷贝，一般的人可能都会用for循环逐个元素进行拷贝，在数据量不大的情况下还可以，如果数据量比较大，那么效率会比较地下。而STL中就提供了一个专门用来进行容器元素拷贝的函数copy。

copy的函数原型如下：

``````template<class InIt, class OutIt>
OutIt copy(InIt first, InIt last, OutIt x);``````

```vector<int> iVec;
for (int i = 0; i < 1000; i ++)
{
iVec.push_back(i+1);
}

int* pInt = new int[iVec.size()];

DWORD t1 = GetTickCount();
std::copy(iVec.begin(),iVec.end(),pInt);
DWORD t2 = GetTickCount();
DWORD tcopy = t2 - t1;

DWORD t3 = GetTickCount();
for (int i = 0; i < 1000; i ++)
{
pInt[i] = iVec[i];
}
DWORD t4 = GetTickCount();
DWORD tcopy2 = t4 - t3;

printf("copy拷贝的时间为：%d\n",tcopy);
printf("for循环拷贝的时间为：%d\n",tcopy2);```

```vector<int> iVec;
for (int i = 0; i < 1000000; i ++)
{
iVec.push_back(i+1);
}

int* pInt = new int[iVec.size()];

DWORD t1 = GetTickCount();
std::copy(iVec.begin(),iVec.end(),pInt);
DWORD t2 = GetTickCount();
DWORD tcopy = t2 - t1;

DWORD t3 = GetTickCount();
for (int i = 0; i < 1000000; i ++)
{
pInt[i] = iVec[i];
}
DWORD t4 = GetTickCount();
DWORD tcopy2 = t4 - t3;

printf("copy拷贝的时间为：%d\n",tcopy);
printf("for循环拷贝的时间为：%d\n",tcopy2);```