How does the range-based for work for plain arrays?

后端 未结 6 1104
暗喜
暗喜 2020-11-27 11:19

In C++11 you can use a range-based for, which acts as the foreach of other languages. It works even with plain C arrays:

int number         


        
6条回答
  •  情深已故
    2020-11-27 11:58

    According to the latest C++ Working Draft (n3376) the ranged for statement is equivalent to the following:

    {
        auto && __range = range-init;
        for (auto __begin = begin-expr,
                  __end = end-expr;
                __begin != __end;
                ++__begin) {
            for-range-declaration = *__begin;
            statement
        }
    }
    

    So it knows how to stop the same way a regular for loop using iterators does.

    I think you may be looking for something like the following to provide a way to use the above syntax with arrays which consist of only a pointer and size (dynamic arrays):

    template 
    class Range
    {
    public:
        Range(T* collection, size_t size) :
            mCollection(collection), mSize(size)
        {
        }
    
        T* begin() { return &mCollection[0]; }
        T* end () { return &mCollection[mSize]; }
    
    private:
        T* mCollection;
        size_t mSize;
    };
    

    This class template can then be used to create a range, over which you can iterate using the new ranged for syntax. I am using this to run through all animation objects in a scene which is imported using a library that only returns a pointer to an array and a size as separate values.

    for ( auto pAnimation : Range(pScene->mAnimations, pScene->mNumAnimations) )
    {
        // Do something with each pAnimation instance here
    }
    

    This syntax is, in my opinion, much clearer than what you would get using std::for_each or a plain for loop.

提交回复
热议问题