fork(1) download
  1. #include <algorithm>
  2. #include <vector>
  3. #include <iterator>
  4. #include <set>
  5. #include <iostream>
  6. #include <numeric>
  7.  
  8. using namespace std;
  9.  
  10. int main()
  11. {
  12. std::vector<int> L = { 1, 2, 4, 3, 2, 4 };
  13. std::set<int> tempSet;
  14. //...
  15. // partition the elements, unique items on left, duplicates on right
  16. auto divider = stable_partition(L.begin(), L.end(), [&](int n)
  17. {
  18. // return true if item is not in the set, false otherwise
  19. return tempSet.insert(n).second;
  20. });
  21.  
  22. // do something with the duplicates, for example, print them
  23. cout << "Here are the dups:\n";
  24. copy(divider, L.end(), ostream_iterator<int>(cout, " "));
  25.  
  26. // get the average
  27.  
  28. // get number of duplicates
  29. size_t numDups = std::distance(divider, L.end());
  30. double avg = 0.0;
  31.  
  32. // compute average using std::accumulate
  33. if ( numDups > 0 )
  34. avg = std::accumulate(divider, L.end(), 0.0) / numDups;
  35. cout << "\nThe average of the duplicates is: " << avg << "\n";
  36.  
  37. // erase the duplicates
  38. L.erase(divider, L.end());
  39.  
  40. // print the updated vector now
  41. cout << "\n\nHere is the resulting vector:\n";
  42. copy(L.begin(), L.end(), ostream_iterator<int>(cout, " "));
  43. }
  44.  
Success #stdin #stdout 0s 3464KB
stdin
Standard input is empty
stdout
Here are the dups:
2 4 
The average of the duplicates is: 3


Here is the resulting vector:
1 2 4 3