fork(1) download
  1. #include <algorithm>
  2. #include <array>
  3. #include <iostream>
  4. #include <utility>
  5. #include <vector>
  6.  
  7. typedef std::pair<int, std::array<char, 3> > Element;
  8. std::vector< Element > v;
  9. std::vector< Element > result;
  10.  
  11. int main()
  12. {
  13. v.push_back( Element(1, std::array<char, 3>{{'a', 'b', 'c'}}) );
  14. v.push_back( Element(2, std::array<char, 3>{{'a', 'b', 'c'}}) );
  15. v.push_back( Element(1, std::array<char, 3>{{'c', 'd', 'e'}}) );
  16. v.push_back( Element(1, std::array<char, 3>{{'b', 'c', 'd'}}) );
  17. v.push_back( Element(3, std::array<char, 3>{{'b', 'c', 'd'}}) );
  18.  
  19. // O(N log(N) ) complexity
  20. std::sort(v.begin(), v.end(), [](Element const& e1, Element const& e2){
  21. // compare the array part of the pair<int, array>
  22. return e1.second < e2.second;
  23. });
  24.  
  25. // O(N) complexity
  26. for (auto it = v.begin(); it != v.end();) {
  27. // find next element
  28. auto last = std::find_if(it, v.end(), [=](Element const& elem){
  29. return it->second != elem.second;
  30. });
  31.  
  32. // accumulate the counts
  33. auto count = std::accumulate(it, last, 0, [](int sub, Element const& elem) {
  34. return sub + elem.first;
  35. });
  36.  
  37. // store count in result
  38. result.push_back( Element(count, it->second) );
  39. it = last;
  40. }
  41.  
  42. for (auto it = result.begin(); it != result.end(); ++it) {
  43. std::cout << it->first << " ";
  44. for (std::size_t i = 0; i < 3; ++i)
  45. std::cout << it->second[i] << " ";
  46. std::cout << "\n";
  47. }
  48. }
Success #stdin #stdout 0s 3020KB
stdin
Standard input is empty
stdout
3 a b c 
4 b c d 
1 c d e