Note that there are some explanatory texts on larger screens.

plurals
  1. POOverloading Iterator: C++ Semantics Question
    primarykey
    data
    text
    <p>Please note this code was not written by me. Otherwise I would not be asking this question. Full credit goes to <a href="https://codereview.stackexchange.com/users/489/jerry-coffin">Jerry Coffin</a>. Anyways the code generates a sequence of numbers by overloading std::iterator&lt; >.</p> <p>I will first post the code, then I will give my interpretation of what I am seeing. If an expert C++ member could correct me if I am wrong I would greatly appreciate it.</p> <p><strong>Code</strong></p> <pre><code>static const int N = 10; template &lt;class T&gt; class sequence : public std::iterator&lt;std::forward_iterator_tag, T&gt; { private: T val; public: sequence(T init) : val(init) { } T operator *( ) { return val; } sequence &amp;operator++( ) { ++val; return *this; } bool operator != ( const sequence &amp;other ) { return val != other.val; } }; void foo( ) { typedef std::vector&lt;int&gt; graph; graph id1( gen_seq(0), gen_seq( N ) ); display( id1 ); /* Not declared */ } /* displays: 0 1 2 3 4 5 6 7 8 9 */ </code></pre> <p>So when looking at this I see that you create a class which contains a value. Now we pass two of those to vector's constructor, which can takes two iterators. Now each time vector's constructor uses the ++ operator on the "sequence" it increments the value inside of the iterator. Technically, you could write:</p> <pre><code>graph id1( gen_seq( 0 ), gen_seq( 0 ) ); </code></pre> <p>and this would generate the same sequence correct? Or is it the != operator that checks to make sure 0 has not gone to N. Any input on this would help greatly. I just finished reading Stroustrup's C++ Programming Language 3rd edition where he touched upon iterators, however inheriting from them was not a big topic and something I am not fully understanding. Kind of whish I would have done all his exercises, because I remember him asking to overload an iterator a few times.</p>
    singulars
    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.
 

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