Anonymous Entity Anonymous Entity - 6 months ago 25
C++ Question

Insert N elements from one container to other using iterators

I want to insert elements that exist in container

to container
in a way that is equivalent to the following:

auto iter = /* iterator from somewhere in A */
for (auto i=0; i<N && iter++ != A.cend(); i++)

But using insert instead and no for loop, something like this;

B.insert(B.end(), iter, iter + N);

#include <algorithm>
#include <iterator>

auto a_iter = /* iterator from somewhere in A */, a_end = A.end();
std::copy_n(a_iter, std::min(N, std::distance(a_iter, a_end)), std::inserter(B, B.end()));

As a standalone algorithm:

template<typename IterT, typename CollT>
std::insert_iterator<CollT> insert_n(
    IterT a_iter, IterT a_end,
    typename std::iterator_traits<IterT>::difference_type N,
    CollT& B
) {
    return std::copy_n(
        std::min(N, std::distance(a_iter, a_end)),
        std::inserter(B, B.end())