Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You say you need a pointer to an iterator... but that's quite confusing and rarely needed.</p> <p>Let's see your solutions, one at a time:</p> <p><strong>Solution 1:</strong></p> <pre><code>vector&lt;type&gt;::iterator *it = &amp;vector&lt;type&gt;::_First; </code></pre> <p>Not valid because <code>_First</code> is private, and also you have to use the <code>vector_object</code>, not the class name.</p> <p><strong>Solution 2:</strong></p> <pre><code>vector&lt;type&gt;::iterator *it = &amp;(vector&lt;type&gt;::begin()); </code></pre> <p>Not valid because <code>begin()</code> is not a static method, so you have to use the object name, not the class name:</p> <pre><code>vector&lt;type&gt;::iterator *it = &amp;(vector_object.begin()); </code></pre> <p>But even then, not valid because <code>begin</code> returns an r-value, and you cannot get the address of such an expression. You have to use an auxiliary variable for that, which will be an l-value.</p> <pre><code>vector&lt;type&gt;::iterator *it = &amp;&amp;(vector&lt;type&gt;[0]); </code></pre> <p>Same as above about the staticness of member functions. It should be:</p> <pre><code>vector&lt;type&gt;::iterator *it = &amp;&amp;(vector_object[0]); </code></pre> <p>But even then, to be fair, this code <em>is</em> crazy. <code>&amp;&amp;</code> is the logical AND operator. You cannot apply operator <code>&amp;</code> (address-of) twice in a row because it has to be applied to an l-values but it returns an r-value. Moreover <code>operator[]</code> returns a value of <code>type</code> not an iterator.</p> <p><strong>Solution 3:</strong></p> <p>This compiles but renders undefined behavior because you are returning the address of a local variable that is destroyed once you return from the function. Returning the address of a local variable is always an error, and most compilers will issue a warning about it.</p> <p>What you have to do is to keep the variable around as long as you need the pointer:</p> <pre><code>vector&lt;type&gt;::iterator it = vector_object.begin(); vector&lt;type&gt;::iterator *pit = &amp;it; // use pit, but keep it around </code></pre> <p>That is, your pointer is valid only as long as <code>it</code> variable exists. That's not something specific to iterators, but to pointers in general.</p> <p>The big question here is: why on earth do you need a pointer to an iterator? I've been programming STL for a very long time and I have never needed a pointer to an iterator before (pointers-to-pointers yes, even pointers-to-pointers-to-pointers, but pointers-to-iterators... never).</p>
 

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