fork download
  1. #include <iostream>
  2. #include <array>
  3. #include <algorithm>
  4.  
  5. using namespace std;
  6.  
  7. template <typename T, size_t N>
  8. void swap_pairs(array<T, N>& arr)
  9. {
  10. bool is_odd = (N % 2 != 0);
  11. auto limit = (is_odd? N - 2 : N - 1);
  12. for (size_t i = 0; i < limit; i += 2) {
  13. swap(arr[i], arr[i + 1]);
  14. }
  15. }
  16.  
  17. template <typename Container>
  18. void print(const Container& c)
  19. {
  20. cout << "{ ";
  21. for (const auto& x : c) {
  22. cout << x << ' ';
  23. }
  24. cout << "}\n";
  25. }
  26.  
  27. int main()
  28. {
  29. array<int, 6> arr_int = {
  30. 1, 2, 3, 4, 5, 6
  31. };
  32. array<double, 5> arr_double = {
  33. 10.5, 9.5, 8.5, 7.5, 6.5
  34. };
  35.  
  36. print(arr_int);
  37. swap_pairs(arr_int);
  38. print(arr_int);
  39.  
  40. print(arr_double);
  41. swap_pairs(arr_double);
  42. print(arr_double);
  43. }
Success #stdin #stdout 0s 4532KB
stdin
Standard input is empty
stdout
{ 1 2 3 4 5 6 }
{ 2 1 4 3 6 5 }
{ 10.5 9.5 8.5 7.5 6.5 }
{ 9.5 10.5 7.5 8.5 6.5 }