title: Getting unique elements from a container [c++]
body: <p>I was looking to get only the unique elements from a container. Let's say <code>srcContainer</code> is the container from which I want unique elements. I looked at three options: </p>
  
  <ol>
  <li><p>Using std::unique  </p>
  
  <pre><code>   std::sort(srcContainer.begin(), srcContainer.end());
     srcContainer.erase(std::unique(srcContainer.begin(), srcContainer.end()), srcContainer.end());
  </code></pre></li>
  <li><p>Using BOOST::unique   </p>
  
  <pre><code>boost::erase(srcContainer, boost::unique&lt;boost::return_found_end&gt;(boost::sort(srcContainer)));  
  </code></pre></li>
  <li><p>My own method   </p>
  
  <pre><code>std::set&lt;T&gt; uniqueElems(srcContainer.begin(), srcContainer.end());  
  srcContainer.clear();  
  srcContainer.insert(srcContainer.end(), uniqueElems.begin(), uniqueElems.end()); 
  </code></pre></li>
  </ol>
  
  <p>The issue with 1. and 2. are that they change the order in which members occurred in the original srcContainer. With 3. there is no change in order, and in addition it gives a much better performance compared to 1. and 2 (Is it because there is no explicit sorting in 3. ??) above. The elapsed wall clock time for 3 methods above and the number of elements in srcContainer are given below: </p>
  
  <ol>
  <li><p>size of srcContainer (contains integers) = 1e+6<br>
      - std::unique =   <strong>1.04779 secs</strong><br>
      - BOOST::unique = <strong>1.04774 secs</strong><br>
      - Own method =    <strong>0.481638 secs</strong>    </p></li>
  <li><p>size of srcContainer (contains integers) = 1e+8<br>
      - std::unique =   <strong>151.554 secs</strong><br>
      - BOOST::unique = <strong>151.474 secs</strong><br>
      - Own method =    <strong>57.5693 secs</strong>  </p></li>
  </ol>
  
  <p>My question is:  </p>
  
  <ol>
  <li>Is there better way to find unique using std::unique or BOOST::unique or any other code and maintaining the original order in the container?  </li>
  <li>Any issue with using method 3. above.  </li>
  </ol>
  
  <p>For performance profiling <code>srcContainer</code> was created as follows:  </p>
  
  <pre><code>std::vector&lt;int&gt; srcContainer;  
  int halfWay = numElems/2;  
  for (size_t k=0; k&lt;numElems; ++k) {  
     if (k &lt; halfWay)  
        srcContainer.push_back(k);  
     else  
        srcContainer.push_back(k - halfWay);  
  }  
  </code></pre>
  
  <p><em>Edits:<br>
  Agreed with comments that method 3. also changes the order of elements. Is there a better way to get unique elements without changing order?</em> </p>
  
  <p>Thanks</p>