What is an iterator in general?

An iterator is an abstraction, everything that behaves like an iterator is an iterator.
In std::vector and std::array it's just a pointer, in other classes it's a class.

write a C++ class template with ctor that accept "general iterator"

Iterator come in pairs. One for the first element , the other that points behind the last element .
1
2
3
4
5
6
7
8
9
10
11
12
13
template<class Iter>
class Demo
{
public:
  Demo(Iter first, Iter last)
  {
    while (first != last)
    {
      // use *first
      ++first;
    }
  }
};
C++ iterator has "concept", which is something concrete to have definitive member names and signatures


http://www.enseignement.polytechnique.fr/informatique/INF478/docs/Cpp/en/cpp/concept/Iterator.html

c++ template and java generic are utterly different in how to realize generic programming, static or dynamic
shouldn't we just call it a "checked pointer"?

because all that one does with iterator is increment, decrement, read and write. and if that fails you get asserted.

I can do all this with plain pointer, except it would much less safe ofc.
Last edited on
I can do all this with plain pointer

not at all: when you increment a pointer, all it does is add a number. When you increment an iterator it could be doing a red-black tree traversal (std::map::iterator), or insertion (insert_iterator), a file write (std::ostreambuf_iterator over an std::ofstream, or a TCP socket read (same, but over asio.tcpstream). That's what makes it a powerful abstraction: all those things use the same pointer-like API, and so you can reuse the same, generic, code like std::copy over any of those things.
Last edited on
@Cubbi

Ah yes indeed!, increment/decrement is not the same as with plain pointers, I missed that xD
Topic archived. No new replies allowed.