std::copy algorithm

function template

std::copy

template <class InputIterator, class OutputIterator> OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result);

the copy range of the element

Copies the elements in the range [first, last) into the range starting at result.

The function returns an iterator to the end of the destination range (it points to the element after the last copied element).

These ranges should not overlap in such a way that the result points to an element in the range [first, last). For this case see  copy_backward .


The behavior of this function template is equivalent to:

template<class InputIterator, class OutputIterator>
  OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result)
{
  while (first!=last) {
    *result = *first;
    ++result; ++first;
  }
  return result;
}

parameter:

first, last

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

result

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

return value

An iterator to the end of the target range of copied elements.

example

// 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;
}


output:

myvector contains: 10 20 30 40 50 60 70

Attached:

copy is only responsible for copying, not for applying for space, so there must be enough space before copying. This code will crash if the size of the container is less than the length N of the input sequence. So at this time back_inserter was introduced, as follows

std::copy(src.begin(), src.end(), std::back_inserter(dest));


The back_inserter template function provided by the standard library is very convenient because it returns a back_insert_iterator iterator for the container, so that the copied elements are appended to the end of the container. (It doesn't matter if the container is empty).

In this case, an alternative is to use back_insert_iterator as the destination parameter. The iterator expands the destination container by expanding elements for each copy, ensuring that the container is large enough to hold each element.
 

Attachment Reference: Link

Guess you like

Origin blog.csdn.net/weixin_58045467/article/details/130834164