Understanding iterator/const_iterator implementation

心不动则不痛 提交于 2020-05-14 11:14:34

问题


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?


回答1:


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 e.g. 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".



来源:https://stackoverflow.com/questions/59262424/understanding-iterator-const-iterator-implementation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!