Search code examples
algorithmc++11stlstandardsstl-algorithm

Why `copy_n`, `fill_n` and `generate_n`?


Why _n versions of the copy, fill and generate have been provided in C++11, and why only these algorithms?


Solution

  • In general, the STL only provides primitives from which one can define suitably adapted variants.

    The SGI documentation gives the following rationale for providing the exceptions you noted:

    • copy_n works for Input Iterators that are not also Forward Iterators.

    • fill_n and generate_n work for Output Iterators that are not also Forward Iterators.

    As pointed out by @Jared Hoberock in the comments, the <memory>header also has uninitialized_ versions of copy_n and fill_n that are optimized versions when the count is already known.

    C++11 provides a few other convenience wrappers (e.g. find_if_not), but with lambda predicates such wrappers become a lot easier to write yourself.

    Note: there is also a search_n but this has different semantics than search because the latter will look at overlap between two input ranges and the former will look at consecutive elements from a single input range.