Anonymous Entity Anonymous Entity - 1 year ago 89
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);

Answer Source
#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())
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download