(C++) std::copy
January 11, 2018 ยท View on GitHub
std::copy is an STL algorithm to copy container elements.
std::copy assumes that the memory data is copied to is valid. For example, if you copy a std::vector of size 10 to another std::vector, the latter must have a size of 10 at least. But if the size is unknown, use an inserter like std::back_inserter.
Related algorithms are:
- std::copy_backward: copy values to the back of a container
- std::copy_if: for performing a conditional copy
- std::transform: for copy and modify
Prefer algorithm calls over hand-written loops [1, 2].
Example: Append
#include <algorithm>
template <class Container>
void append(Container& to, const Container& from)
{
std::copy(std::begin(from), std::end(from), std::back_inserter(to));
}
Example: CoutVector
#include <iostream>
#include <iterator>
#include <ostream>
#include <vector>
template <class T>
void cout_vector(const std::vector<T>& v)
{
std::copy(std::begin(v), std::end(v), std::ostream_iterator<T>(std::cout,"\n"));
}
External links
References
- [1] Bjarne Stroustrup. The C++ Programming Language (3rd edition). ISBN: 0-201-88954-4. Chapter 18.12.1: 'Prefer algorithms to loops.
- [2] Scott Meyers. Effective STL. ISBN: 0-201-74962-9. Item 43: 'Prefer algorithm calls over hand-written loops'