What is an iterator in general?

  • A+
Category:Languages

This problem comes up when I tried to write a class template with ctor that accept "general iterator". I don't know if it's appropriate to use the word general here, but what I mean is that it can accept iterator just like STL container.

In other word, I'm confused about iterator. It seems that all STL container has the same type iterator, so what's that type? Is it just pointer? Or something more complicated? But STL container do accept normal pointer.

(I would like to compare it to Iterator<T> in Java, which is quite simple and it's just a class)

 


In C++ an Iterator is a concept, not a concrete (or abstract) type, but any type that obeys certain iterator like rules.

For example iterators generally can be incremented ++i. They can be accessed (dereferenced) *i to obtain the value they currently point to. They are essentially abstractions of a pointer.

In the Standard Library's containers & algorithms there are different kinds of iterators with different properties. Their properties are listed here:

https://en.cppreference.com/w/cpp/iterator

So when writing algorithms in C++ that accept iterators, generally just accept generic template parameters and use the appropriate iterator properties in the function. The compiler will complain if the user passes something to your function that doesn't obey the iterator rules:

template<typename ForwardIter> void my_algorithm(ForwardIter begin, ForwardIter end) {     for(; begin != end; ++begin)         std::cout << *begin << '/n'; } 

You can add a whole bunch of specific checks to make sure the user passed something sensible, but that's too broad for this question.

Note:

Whilst currently concepts, such as Iterator, are merely a set of agreed upon semantic properties in the Standard that programmers must follow, a more comprehensive solution that will formalize such concepts (in code) is intended for the next version of the Standard, C++20.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: