std::copy使用方法

本文介绍了C++标准库中用于复制元素的算法`copy`,并提供了详细的参数说明及使用示例。`copy`可以将指定范围内的元素复制到另一个范围,适用于多种迭代器类型。

推荐2个c++函数库,类定义的资料库:

http://en.cppreference.com/w/cpp/algorithm/copy

http://www.cplusplus.com/reference/algorithm/copy/?kw=copy

---------------------------------------------------------------------------------------------------------------

Defined in header <algorithm>
template< class InputIt, class OutputIt >
     OutputIt copy( InputIt first, InputIt last, OutputIt d_first );

Copies the elements in the range, defined by [first, last), to another range beginning at d_first

Parameters

first, last

            Input iterators to the initial and final positions in a sequence to be copied. The range used is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.

            c++中的区间几乎都是左开右闭的,包括一些类的构造函数,比如 int a[5] = { 1, 2, 3, 4, 5};  set<int> s(&a[0], &a[4]); s里只会插入{ 1,2,3,4 }这4个元素。

d_first

            Output iterator to the initial position in the destination sequence.
            This shall not point to any element in the range [first,last).

Return value

An iterator to the end of the destination range where elements have been copied.

Complexity

Linear in the distance between first and last: Performs an assignment operation for each element in the range.

Example

The following code uses copy to both copy the contents of one vector to another and to display the resulting vector:

#include <algorithm>
#include <iostream>
#include <vector>
#include <iterator>
#include <numeric>
 
int main()
{
    std::vector<int> from_vector(10);
    std::iota(from_vector.begin(), from_vector.end(), 0);
 
    std::vector<int> to_vector;
    std::copy(from_vector.begin(), from_vector.end(),
              std::back_inserter(to_vector));
// or, alternatively,
//  std::vector<int> to_vector(from_vector.size());
//  std::copy(from_vector.begin(), from_vector.end(), to_vector.begin());
// either way is equivalent to
//  std::vector<int> to_vector = from_vector;
 
    std::cout << "to_vector contains: ";
 
    std::copy(to_vector.begin(), to_vector.end(),
              std::ostream_iterator<int>(std::cout, " "));
    std::cout << '\n';
}

 

Output:

to_vector contains: 0 1 2 3 4 5 6 7 8 9

转载于:https://www.cnblogs.com/scw2901/p/4228880.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值