Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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: ...
like image 893
Posco Grubb Avatar asked Jun 30 '09 05:06

Posco Grubb


People also ask

What is a const_iterator?

A const_iterator is an iterator that points to const value (like a const T* pointer); dereferencing it returns a reference to a constant value ( const T& ) and prevents modification of the referenced value: it enforces const -correctness.

How do I make a custom iterator?

To use custom iterators, you must create an Apex class that implements the Iterator interface. Returns true if there's another item in the collection being traversed, false otherwise. Returns the next item in the collection. All methods in the Iterator interface must be declared as global or public .

What is the difference between Cbegin and begin?

begin() returns an iterator to beginning while cbegin() returns a const_iterator to beginning. The basic difference between these two is iterator (i.e begin() ) lets you change the value of the object it is pointing to and const_iterator will not let you change the value of the object.

How are iterators implemented in C++?

The iterator is implemented as a pointer to a node, and contains operator overloads for the four usual iterator operations of dereference, increment, comparison, and assignment. in the list class that can be used to insert new data items at arbitrary locations in the list.


2 Answers

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)

like image 21
Todd Gardner Avatar answered Sep 28 '22 10:09

Todd Gardner


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.

like image 159
Martin York Avatar answered Sep 28 '22 10:09

Martin York