Is there a standard C++ equivalent of IEnumerable in C#?

后端 未结 4 728
有刺的猬
有刺的猬 2020-12-04 16:44

Or is it safe to use vector if the Enumerator of T is just listing all the elements?

4条回答
  •  执笔经年
    2020-12-04 17:09

    IEnumerable is conceptually very different from vector.

    The IEnumerable provides forward-only, read-only access to a sequence of objects, regardless of what container (if any) holds the objects. A vector is actually a container itself.

    In C++, should you want to provide access to a container without giving the details of this container, the convention is to pass in two iterators representing the beginning and end of the container.

    A good example is the C++ STL definition of accumulate, which can be contrasted with IEnumerable.Aggregate

    In C++

       int GetProduct(const vector& v)
       {
             // We don't provide the container, but two iterators
             return std::accumulate(v.begin(), v.end(), 1, multiplies());
       }
    

    In C#

      int GetProduct(IEnumerable v)
      {
            v.Aggregate(1, (l, r) => l*r);
      }
    

提交回复
热议问题