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

Insert N elements from one container to other using iterators

I want to insert elements that exist in container

A
to container
B
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++)
B.push_back(*iter);


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

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

Answer
#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(
        a_iter,
        std::min(N, std::distance(a_iter, a_end)),
        std::inserter(B, B.end())
    );
}
Comments