Better Way to Write this Code?

Is there a better way I could have written this trivial program? Basically, it takes an n-sized array of an arbitrary type and reverses all the elements (Yes, I know there are standard library algorithms that do this better. This was merely practice).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
 //Takes all elements in n-size array of an arbitrary type and reverses the order.
#include <iostream> //for std::cout
#include <string>   //for std::string

using namespace std::string_literals; //Allows the use of operator""s without having to use all of std

template <typename T> 
static inline void Swap(T& a, T& b) { T temp = a; a = b; b = temp;}

template <typename T, size_t numElts> 
static void ReverseArray(T(&a)[numElts]) //void ReverseArray(std::array<T, numElts>) 
{ 
    for(size_t k=0, limit = numElts/2; k < limit; k++) Swap(a[k], a[numElts-k-1]);
}


int main(/*argc, argv*/)
{
  //Test ReverseArray()
  std::string array[3] = {"a"s,"b"s,"c"s}; 
  std::cout << "original :" << std::endl;
  for (const auto& a : array) { std::cout << a << " "; }
  std::cout << std::endl << std::endl;
  
  ReverseArray(array);
  std::cout << "after: " <<std::endl;
  for (const auto& a : array) {std::cout << a << " ";}
  std::cout << std::endl;
  return 0;
}
Last edited on
Without using the library:

Our custom swap should attempt to move construct / move assign.
1
2
template < typename T > void Swap( T& a, T& b )
{ T temp = std::move(a) ; a = std::move(b) ; b = std::move(temp) ; }


This is another way to write reverse (not any better; just different):
1
2
template < typename T, std::size_t N > void ReverseArray( T (&a) [N] )
{ for( auto left = a, right = a+N-1 ; left < right ; ++left, --right ) Swap( *left, *right ) ; 


Ideally, both should be marked noexcept if T is both no throw move constructible and no throw move assignable.

http://coliru.stacked-crooked.com/a/e31e6166a153ec9a
Last edited on
I didn't even think to use move semantics. It definitely makes sense if the array elements are objects of a class.

Thank you.

EDIT:

What exactly does this line do?
right = a+N-1;

I understand that right would be a pointer to the array. Would it simply equal the last element in the array? ("a" would be the first element, incrementing the pointer by N-1 returns last element?)
Last edited on
> "a" would be the first element, incrementing the pointer by N-1 returns last element?

Yes, a pointer to the actual last element in the array.

With int a[100], the addresses of the 100 elements in the array would be a+0, a+1, a+2, ... , a+98, a+99
Topic archived. No new replies allowed.