C++ STL: Can arrays be used transparently with STL functions?

后端 未结 11 1295
半阙折子戏
半阙折子戏 2020-12-15 17:07

I was under the assumption that STL functions could be used only with STL data containers (like vector) until I saw this piece of code:

#include         


        
11条回答
  •  感情败类
    2020-12-15 18:02

    The standard has designed iterators to feel and behave as much like pointers as possible. Also, since iterators are based on templates, the only relevant thing is that the iterator type has the proper operators defined. The result is that pointers will out-of-the-box behave just like random access iterators.

    In fact, a possible implementation of std::vector::iterator is to just make it a T*.

    Of course, for an array you won't have the useful begin() and end() methods to find the valid iterator range, but that's the problem you always have with C style arrays.

    Edit: Actually, as has been mentioned in the comments and other answers, you can implement those functions for arrays if the array is not dynamic and has not decayed into a pointer. But my basic point was that you have to be more careful than when using the standard containers.

提交回复
热议问题