fork 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. struct setPredicate
  11. {
  12. std::set<int>* p_set;
  13. setPredicate(std::set<int>* pSet) : p_set(pSet) {}
  14. bool operator()(int n)
  15. { return p_set->insert(n).second; }
  16. };
  17.  
  18. int main()
  19. {
  20. int testData [] = { 1, 2, 4, 3, 2, 4 };
  21. std::vector<int> L(testData, testData + 6);
  22. std::set<int> tempSet;
  23. //...
  24. // partition the elements, unique items on left, duplicates on right
  25. std::vector<int>::iterator divider =
  26. stable_partition(L.begin(), L.end(), setPredicate(&tempSet));
  27.  
  28. // do something with the duplicates, for example, print them
  29. cout << "Here are the dups:\n";
  30. copy(divider, L.end(), ostream_iterator<int>(cout, " "));
  31.  
  32. // get the average
  33.  
  34. // get number of duplicates
  35. size_t numDups = std::distance(divider, L.end());
  36. double avg = 0.0;
  37.  
  38. // compute average using std::accumulate
  39. if ( numDups > 0 )
  40. avg = std::accumulate(divider, L.end(), 0.0) / numDups;
  41. cout << "\nThe average of the duplicates is: " << avg << "\n";
  42.  
  43. // erase the duplicates
  44. L.erase(divider, L.end());
  45.  
  46. // print the updated vector now
  47. cout << "\n\nHere is the resulting vector:\n";
  48. copy(L.begin(), L.end(), ostream_iterator<int>(cout, " "));
  49. }
  50.  
Success #stdin #stdout 0s 2864KB
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