Posco Grubb
Posco Grubb

Reputation: 522

C++ : How to write a const_iterator?

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

Upvotes: 10

Views: 10989

Answers (3)

Ben FrantzDale
Ben FrantzDale

Reputation: 1

Roger Pate, value_types are "simple". I suspect you'll see the const if you look at iterator_traits::const_iterator>::reference, which I think will be "const int&".

Upvotes: 0

Todd Gardner
Todd Gardner

Reputation: 13521

I find the easiest way to implement iterators is boost::iterator. If you want to roll your own, I think the signature should be:

class const_iterator : public std::iterator<std::bidirectional_iterator_tag, const T> {

with the implementation the same (assuming you are using reference_type and so forth in your function signatures)

Upvotes: 3

Loki Astari
Loki Astari

Reputation: 264739

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.

Upvotes: 5

Related Questions