问题
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::vectoris a class template in the std namespace, which makesstd::vector<double>a class.
std::vector<T>::iteratoris a nested type understd::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?
回答1:
Gathered information from the comments:
std::iteratorfrom#include <iterator>is deprecated as of C++17Before it was deprecated, it was possible for STL containers (which are implementation defined) to implemented iterators with the help of the
std::iteratortemplate class.For
vectorfor example:There is nothing in the specification of
std::vectorthat saysvector::iteratororvector::const_iteratorhave any particular relationship tostd::iterator(even in standards predating deprecation ofstd::iterator). Also, althoughiteratorandconst_iteratorare types declared in the scope ofvector, there is no requirement thatvectorhave a member of either type -iteratorandconst_iteratorare part of the interface ofstd::vectore.g. overloads of the memberbegin()returns those types, but nothing is said about how those function obtain the iterator they returnWhat 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 likeLegacyRandomAccessIteratorwhich defined as "A pointer to an element of an array satisfies all requirements ofLegacyRandomAccessIterator".
来源:https://stackoverflow.com/questions/59262424/understanding-iterator-const-iterator-implementation