Search code examples
c++c++11iota

Why didn't they add an operator version of iota?


The iota template function was added to the standard library to fill an iterator range with an increasing sequence of values.

  template<typename ForwardIterator, typename Tp>
    void
    iota(ForwardIterator first, ForwardIterator last, Tp value)
    {
      for (; first != last; ++first)
        {
          *first = value;
          ++value;
        }
    }

Most other templates in <numeric> have versions that accept user-specified operators. Having this:

  template<typename ForwardIterator, typename Tp, typename Operator>
    void
    iota(ForwardIterator first, ForwardIterator last, Tp value, Operator op)
    {
      for (; first != last; ++first)
        {
          *first = value;
          op(value);
        }
    }

would be convenient if you don't want to (or can't) overload operator++() for Tp. I would find this version more widely usable than the default operator++() version. <


Solution

  • With lambdas, the second version doesn't save much, you can just use std::generate.

    template<typename ForwardIterator, typename Tp, typename Operator>
    void iota(ForwardIterator first, ForwardIterator last, Tp value, Operator op)
    {
      std::generate(first, last, [&value,&op](){auto v = value; op(value); return v;});
    }
    

    In fact, this makes the existing implementation of std::iota very redundant:

    template<typename ForwardIterator, typename Tp>
    void iota(ForwardIterator first, ForwardIterator last, Tp value)
    {
      std::generate(first, last, [&value](){return value++;});
    }