C++ : How to write a const_iterator?

Posco Grubb picture Posco Grubb · Jun 30, 2009 · Viewed 9.2k times · Source

I've written my own container template with an iterator. How do I implement const_iterator?

template <class T>
class my_container {
 private:
  ...

 public:
  my_container() : ... { }
  ~my_container() { }

  class iterator : public std::iterator<std::bidirectional_iterator_tag, T> {
  public: ...

Answer

Martin York picture Martin York · Jun 30, 2009

The only difference should be that when you de-reference a const iterator you get a const reference rather than a reference to the object in the container.