csguy
csguy

Reputation: 1474

Relationship of iterators and STL containers

I understand the general idea behind iterators and I can use them at a basic level, but I don't get what happens under the hood and the relationship they have with STL containers.

From reading http://www.cplusplus.com/reference/iterator/iterator/:

My assumptions are (I will be using vector throughout as an example)

I hope I am making sense, please correct me.

Upvotes: 1

Views: 648

Answers (1)

Caleth
Caleth

Reputation: 62704

Let's go point by point.

Iterators are objects defined with a class template

Not necessarily. Iterators are objects that have certain operations. Pointers are such objects, as are objects of various class types.

Each container defines a member type container::iterator, and another member type container::const_iterator.

These can be directly (a nested class), or it could be with a type alias referring to some other typename.

Iterators are classified into five categories depending on the functionality they implement

As of C++14, yes. C++17 and C++20 each introduce another category.

There are different types of iterators (input, output, forward, bidirectional, random access)

Those are the (C++14) categories, but there are an infinity of types within each category. std::vector<int>::iterator is a random access iterator, and so is double *, but they are distinct types. These categories overlap, the definitions are in terms of previous ones in the hierachy. RandomAccess is defined as an extension to Bidirectional, which is defined as an extension to Forward, which is defined as an extension to Input.

In STL containers, for example vector, the iterator is a nested class template and is created for each unique vector type.

Mostly. In many implementations it is, but in the particular case of std::vector<T>, no rule stops an implementation from using T * as the iterator type.

An iterator being considered to be one particular type of iterators is just a concept because it ultimately depends on what is implemented as member functions in the vector class.

Yes. C++ has a notion Concept, which are just labels for things that behave in similar ways. Because of how templates work, there does not need to be any relationship between the types that satisfy a particular Concept. Contrast Java and C#, where interfaces have to be explicitly mentioned in the definition of a type.

Functions like begin() and end() are overloaded in the vector class

This is literally true, but probably not what you mean. Each container does have two member functions named begin. container::iterator container::begin() and container::const_iterator container::begin() const.

There is also the free function template std::begin, which is specialised for each container and also (C style) arrays.

Upvotes: 1

Related Questions