简体   繁体   中英

Understanding iterator/const_iterator implementation

I know how to use iterators on a surface level, but I am trying to understand how iterators work in relation to a container class such as vector .

According to why do we put :: (scope resoulation operator) before iterator?

std::vector is a class template in the std namespace, which makes std::vector<double> a class.

std::vector<T>::iterator is a nested type under std::vector<T>

From what I understand, the class template vector has a member of type iterator which it gets from the class template in #include <iterator> .

This is confusing because when I look in http://www.cplusplus.com/reference/iterator/iterator/ there is no const_iterator class template in #include <iterator> that I can see?

Gathered information from the comments:

  • std::iterator from #include <iterator> is deprecated as of C++17

  • Before it was deprecated, it was possible for STL containers (which are implementation defined) to implemented iterators with the help of the std::iterator template class.

  • For vector for example:

    There is nothing in the specification of std::vector that says vector::iterator or vector::const_iterator have any particular relationship to std::iterator (even in standards predating deprecation of std::iterator ). Also, although iterator and const_iterator are types declared in the scope of vector , there is no requirement that vector have a member of either type - iterator and const_iterator are part of the interface of std::vector eg overloads of the member begin() returns those types, but nothing is said about how those function obtain the iterator they return

  • What is and isn't required in a STL container is:

    "a begin and end function that returns iterators (or raw pointers as that satisfies the requirements for an iterator). There is nothing that says the iterator needs to be implemented in the container."

  • STL containers define those member types ( iterator , const_iterator , etc) usually with type alias for some iterator category like LegacyRandomAccessIterator which defined as "A pointer to an element of an array satisfies all requirements of LegacyRandomAccessIterator ".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM