snippetcppCritical
How to correctly implement custom iterators and const_iterators?
Viewed 0 times
howiteratorsandconst_iteratorscorrectlyimplementcustom
Problem
I have a custom container class for which I'd like to write the
I never did this before and I failed to find an appropriate how-to. What are the guidelines regarding iterator creation, and what should I be aware of ?
I'd also like to avoid code duplication (I feel that
Foot note: I'm pretty sure Boost has something to ease this but I can't use it here, for many stupid reasons.
iterator and const_iterator classes.I never did this before and I failed to find an appropriate how-to. What are the guidelines regarding iterator creation, and what should I be aware of ?
I'd also like to avoid code duplication (I feel that
const_iterator and iterator share many things; should one subclass the other ?).Foot note: I'm pretty sure Boost has something to ease this but I can't use it here, for many stupid reasons.
Solution
- Choose type of iterator which fits your container: input, output, forward etc.
- Use base iterator classes from standard library. For example,
std::iteratorwithrandom_access_iterator_tag.These base classes define all type definitions required by STL and do other work.
-
To avoid code duplication iterator class should be a template class and be parametrized by "value type", "pointer type", "reference type" or all of them (depends on implementation). For example:
// iterator class is parametrized by pointer type
template class MyIterator {
// iterator class definition goes here
};
typedef MyIterator iterator_type;
typedef MyIterator const_iterator_type;Notice
iterator_type and const_iterator_type type definitions: they are types for your non-const and const iterators.See Also: standard library reference
EDIT:
std::iterator is deprecated since C++17. See a relating discussion here.Code Snippets
// iterator class is parametrized by pointer type
template <typename PointerType> class MyIterator {
// iterator class definition goes here
};
typedef MyIterator<int*> iterator_type;
typedef MyIterator<const int*> const_iterator_type;Context
Stack Overflow Q#3582608, score: 184
Revisions (0)
No revisions yet.