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

后端 未结 4 729
有刺的猬
有刺的猬 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:08

    The standard C++ way is to pass two iterators:

    template
    void some_function(ForwardIterator begin, ForwardIterator end)
    {
        for (; begin != end; ++begin)
        {
            do_something_with(*begin);
        }
    }
    

    Example client code:

    std::vector vec = {2, 3, 5, 7, 11, 13, 17, 19};
    some_function(vec.begin(), vec.end());
    
    std::list lst = {2, 3, 5, 7, 11, 13, 17, 19};
    some_function(lst.begin(), lst.end());
    
    int arr[] = {2, 3, 5, 7, 11, 13, 17, 19};
    some_function(arr + 0, arr + 8);
    

    Yay generic programming!

提交回复
热议问题