C++ what is an iterator in general?

  • A+

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 sth 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:


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.


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