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

后端 未结 11 1344
半阙折子戏
半阙折子戏 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 17:48

    Short answer: STL algorithms are generally defined to work with iterators of various sorts. An iterator is defined by its behavior: it must be dereferenceable with *, it must be incrementable with ++, and various other things that also define what sort of iterator it is (the most general is random access). Remember that STL algorithms are templates, so the question is one of syntax. Similarly, a class instance with operator() defined works syntactically just like a function, so they can be used interchangeably.

    A pointer does everything needed to be a random-access iterator. Therefore, it is a random-access iterator, and can be used as such in STL algorithms. You could look at vector implementations; you're very likely to find that vector::iterator is a whatever *.

    This doesn't make an array a valid STL container, but it does make pointers valid STL iterators.

提交回复
热议问题