std::
copy
函数模板 <algorithm>
template <class InputIterator, class OutputIterator>
OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result); |
复制范围的元素
将范围[first,last]中的元素复制到从result开始的范围中。
该函数返回目标范围末尾的迭代器(指向最后一个复制的元素后面的元素)。
范围不应重叠,例如result指向范围[first,last)中的一个元素。对于这种情况,请参阅copy_backward。
这个函数模板的行为相当于:
template<class InputIterator, class OutputIterator>
OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result)
{
while (first!=last) {
*result = *first;
++result; ++first;
}
return result;
} |
☲ 参数
-
first, last
-
指向一个序列初始和最终位置的输入迭代器。使用的范围是[first,last),
它包含first和last之间的所有元素,包括first指向的元素,但不包括last指向的元素。
-
result
-
指向目标序列中的初始位置的输出迭代器。
这将不会指向范围[first,last)中的任何元素。
☉ 返回值
指向复制元素的目标范围末尾的迭代器。
☣ 示例
// copy algorithm example
#include <iostream> // std::cout
#include <algorithm> // std::copy
#include <vector> // std::vector
int main () {
int myints[]={10,20,30,40,50,60,70};
std::vector<int> myvector (7);
std::copy ( myints, myints+7, myvector.begin() );
std::cout << "myvector contains:";
for (std::vector<int>::iterator it = myvector.begin(); it!=myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
} |
输出:
myvector contains: 10 20 30 40 50 60 70
✥ 复杂度
first and last之间的距离是线性的:对范围内的每个元素执行赋值操作。
⇄ 数据竞争
访问[first,last]范围内的对象(每个对象只访问一次)。
result和返回值之间的对象被修改(每个对象只修改一次)。
☂ 异常安全性
如果迭代器上的元素赋值或操作抛出,则抛出。
注意,无效的参数会导致未定义的行为。
🍄 另请参阅
copy_backward |
从末尾复制范围的元素(函数模板) |
fill |
在范围内查找值(函数模板) |
replace |
从设置的范围查找元素(函数模板) |