What would be a good implementation of iota_n (missing algorithm from the STL)

Viewed 1464

With C++11, the STL has now a std::iota function (see a reference). In contrast to std::fill_n, std::generate_n, there is no std::iota_n, however. What would be a good implementation for that? A direct loop (alternative 1) or delegation to std::generate_n with a simple lambda expression (alternative 2)?

Alternative 1)

template<class OutputIterator, class Size, class T>
OutputIterator iota_n(OutputIterator first, Size n, T value)
{
        while (n--)
                *first++ = value++;
        return first;
}

Alternative 2)

template<class OutputIterator, class Size, class T>
OutputIterator iota_n(OutputIterator first, Size n, T value)
{
        return std::generate_n(first, n, [&](){ return value++; });
}    

Would both alternatives generate equivalent code with optimizing compilers?

UPDATE: incorporated the excellent point of @Marc Mutz to also return the iterator at its destination point. This is also how std::generate_n got updated in C++11 compared to C++98.

4 Answers

A hypothetical iota_n

std::iota_n(first, count, value)

can be replaced by a one liner.

std::generate_n(first, count, [v=value]()mutable{return v++;})

I prefer this to have a lingering function that is not in the standard. Having said that, I think a std::iota_n should be in the standard.

Probably use back_insertor along with std::generate_n so that pre-allociton of collections can be avoided.

vector<int> v3;
generate_n(back_inserter(v3),10,[i=1]() mutable{
    return i++;
});

We can swap this for iota_n till we get iota_n :)

Related