Skip to content

Copy a range of elements

cpppatterns Copy a range of elements

NOTE: 原文描述了三种情况的copy a range of elements:

  • copy the elements from the source range into a container
  • copy the elements of source into a range or container which already has the appropriate number of elements allocated
  • copy into a container that does not yet contain any elements

foo函数,使用 std::beginstd::end ,这就限制了RangeOfInts必须要支持这两种operation。阅读std::begin, std::cbegin#User-defined overloads节可知,可以通过提供user-defined overload来使user defined type支持std::beginstd::end;最好的做法是:结合Range-based algorithms中的做法,采用类似于swap idiom的方式来实现。

#include <vector>
#include <algorithm>
#include <iterator>

std::vector<int> target2(5);
std::vector<int> target3;

template<typename RangeOfInts>
void foo(RangeOfInts source)
{
    std::vector<int> target1 { std::begin(source),
            std::end(source) }; // 情况1
    std::copy(std::begin(source), std::end(source),
            std::begin(target2)); // 情况2
    std::copy(std::begin(source), std::end(source),
            std::back_inserter(target3)); // 情况3
}

int main()
{

}

INTENT

Copy elements from a range to another range or container.

NOTE: 函数foo的入参是range

DESCRIPTION

情况1

On lines 11–12, we copy the elements from the source range into a container, target1, simply by passing the begin and end iterators of the range to the std::vector<T>’s constructor. We use std::begin and std::end to obtain these iterators.

情况2

To copy the elements of source into a range or container which already has the appropriate number of elements allocated, represented by target2 on line 5, we use std::copy on lines 14–15. The first two iterator arguments denote the source range, and the third iterator argument denotes the start of the target range. For this to work, the elements must already exist in the target range.

情况3

To demonstrate how we can copy into a container that does not yet contain any elements, we have an empty std::vector<int> called target3 on line 6. For the third argument of std::copy (lines 17–18), we call std::back_inserter to get an iterator that automatically calls push_back on target3 for each element that is copied.