fork download
  1. #include <iostream>
  2.  
  3. template <typename T>
  4. void unique(T* t, std::size_t& size)
  5. {
  6. T* end = t + size;
  7.  
  8. // find the first duplicate:
  9. T* current = t;
  10. while (current != end && current + 1 != end && *current != *(current + 1))
  11. ++current;
  12.  
  13. ++current;
  14.  
  15. // point source at the next different element
  16. T* source = current + 1;
  17. while (source != end && source + 1 != end && *source == *current)
  18. ++source;
  19.  
  20. while (source != end)
  21. {
  22. *current++ = *source++;
  23.  
  24. // advance source to the next different element
  25. if (source != end && *(source - 1) == *source)
  26. ++source;
  27. }
  28.  
  29. // current is pointing to the new end element, so:
  30. size = current - t;
  31. }
  32.  
  33. template <typename T>
  34. void print(const T& ra_container, std::size_t size)
  35. {
  36. std::cout << "[ ";
  37. for (std::size_t i = 0; i < size; ++i)
  38. std::cout << ra_container[i] << ' ';
  39. std::cout << ']';
  40. }
  41.  
  42. int main()
  43. {
  44. int data[2][10] = { {1, 1, 1, 1, 1, 1, 1, 1, 1, 9}, {2, 2, 4, 4, 6, 6, 8, 8, 10, 10} };
  45. std::size_t sizes[2] = { 10, 10 };
  46.  
  47.  
  48. for (std::size_t i = 0; i < 2; ++i)
  49. {
  50. print(data[i], sizes[i]);
  51. std::cout << " => ";
  52.  
  53. unique(data[i], sizes[i]);
  54.  
  55. print(data[i], sizes[i]);
  56. std::cout << '\n';
  57. }
  58. }
Success #stdin #stdout 0s 3412KB
stdin
Standard input is empty
stdout
[ 1 1 1 1 1 1 1 1 1 9 ] => [ 1 9 ]
[ 2 2 4 4 6 6 8 8 10 10 ] => [ 2 4 6 8 10 ]