Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I agree with <a href="https://stackoverflow.com/questions/1041620/most-efficient-way-to-erase-duplicates-and-sort-a-c-vector/1041874#1041874">R. Pate</a> and <a href="https://stackoverflow.com/questions/1041620/most-efficient-way-to-erase-duplicates-and-sort-a-c-vector/1041700#1041700">Todd Gardner</a>; a <a href="http://en.cppreference.com/w/cpp/container/set" rel="noreferrer"><code>std::set</code></a> might be a good idea here. Even if you're stuck using vectors, if you have enough duplicates, you might be better off creating a set to do the dirty work.</p> <p>Let's compare three approaches:</p> <p><strong>Just using vector, sort + unique</strong></p> <pre><code>sort( vec.begin(), vec.end() ); vec.erase( unique( vec.begin(), vec.end() ), vec.end() ); </code></pre> <p><strong>Convert to set (manually)</strong></p> <pre><code>set&lt;int&gt; s; unsigned size = vec.size(); for( unsigned i = 0; i &lt; size; ++i ) s.insert( vec[i] ); vec.assign( s.begin(), s.end() ); </code></pre> <p><strong>Convert to set (using a constructor)</strong></p> <pre><code>set&lt;int&gt; s( vec.begin(), vec.end() ); vec.assign( s.begin(), s.end() ); </code></pre> <p>Here's how these perform as the number of duplicates changes:</p> <p><img src="https://i.stack.imgur.com/gGgtR.png" alt="comparison of vector and set approaches"></p> <p><strong>Summary</strong>: when the number of duplicates is large enough, <em>it's actually faster to convert to a set and then dump the data back into a vector</em>. </p> <p>And for some reason, doing the set conversion manually seems to be faster than using the set constructor -- at least on the toy random data that I used.</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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. 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