Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This is a fixed implementation, of what you had in your code:</p> <pre><code>template &lt;typename Container, typename Arg&gt; void move_x(Container&amp; c, Arg x) { typename Container::iterator it = find(c.begin(), c.end(), x); if (it!=c.end()) { c.erase(it); c.insert(c.end(), x); } } </code></pre> <p>One issue with your implementation is that <code>insert</code> anywhere <a href="http://www.cplusplus.com/reference/vector/vector/insert/" rel="nofollow noreferrer">but the end</a> can cause a reallocation and regardless will invalidate anything after the inserted position. So by definition since you are inserting at the beginning <code>it</code> will not be valid.</p> <p>The second issue is with <code>cout&lt;&lt;v[i];</code> it should actually be <code>cout&lt;&lt;i;</code>.</p> <p>A nicer implementation that uses reverse iterators and moves all <code>x</code>s. This one erases as it goes and keeps a <code>count</code> and then does <code>count</code> inserts when done. Using <a href="https://stackoverflow.com/questions/1830158/how-to-call-erase-with-a-reverse-iterator">erase with reverse iterators</a> is a little tricky:</p> <pre><code>template &lt;typename Container, typename Arg&gt; void move_all_x(Container&amp; c, Arg x) { unsigned int count = 0 ; for( typename Container::reverse_iterator it = c.rbegin() ; it != c.rend(); ) { if( *it == x ) { c.erase(--(it++).base() ) ; ++count ; } else { ++it ; } } for( unsigned int i = 0; i &lt; count; ++i ) { c.insert(c.begin(), x) ; } } </code></pre>
    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.
    1. VO
      singulars
      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