Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Do not cast the const away, as it will break its meaning! There is a reason why the STL has a const_iterator and iterator class. If you want const correctness you will have to implement two seperate iterator classes. One of the goals of a iterator is to mimic a save pointer. So you do not want to return null if you're beyond the iteration range, you want to raise a debug assertion if this actually happens.</p> <p>A const iterator class could look something like this:</p> <pre><code>template&lt;class Item&gt; class DFSIteratorConst { public: DFSIteratorConst(const Item&amp; node) { m_pCurrentNode = &amp;node; }; const Item&amp; operator*() const { assert(!IsDone()); return *m_pCurrentNode; } void operator++() { assert(!IsDone()); m_pCurrentNode = m_pCurrentNode-&gt;next; } operator bool() const { return !IsDone(); } bool IsDone() const { return m_pCurrentNode == nullptr; } private: Item const * m_pCurrentNode; }; </code></pre> <p>A few things to note:</p> <ul> <li>consider returning a reference to the node (a const reference). This causes you to not be able to return null if the iterator is past the last element. Dereferencing a past the end iterator is usually bad behaviour and you want to find those issues during debug builds and testing</li> <li>the const iterator class has a pointer to a const element. Meaning that it can change the pointer (otherwise you would not be able to iterate) but can <strong><em>not</em></strong> modify the element itself</li> <li>the implicit conversion to bool is practical if you want to check the iterator in a while loop. This allows you to write: <code>while(it) { it++; }</code> instead of <code>while(!it.IsDone()) { it++; }</code> again, something that resembles a classic pointer.</li> <li>use <a href="http://en.wikibooks.org/wiki/More_C++_Idioms/nullptr" rel="nofollow" title="nullptr">nullptr</a> if available</li> </ul> <p>As I can see from your use of <code>std::map</code> your are already using the STL. Maybe it would be easier to use exsiting STL iterators?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload