What is the difference between &vector[0] and vector.begin()?

前端 未结 3 1378
故里飘歌
故里飘歌 2021-01-13 07:50

This question is related with item 16 of effective stl book which states that while using vector(lets assume vectorvec) instead of array in a legacy

3条回答
  •  一个人的身影
    2021-01-13 08:40

    vec.begin() has type std::vector::iterator. &vec[0] has type pointer to std::vector::value_type. These are not necessarily the same type.

    It is possible that a given implementation uses pointers as the iterator implementation for a vector, but this is not guaranteed, and thus you should not rely on that assumption. In fact most implementations do provide a wrapping iterator type.

    Regarding your question about pointers being iterators, this is partly true. Pointers do meet the criteria of a random access iterator, but not all iterators are pointers. And there are iterators that do not support the random access behavior of pointers.

提交回复
热议问题