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: ...
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.
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 .
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.
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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With