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).
//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
usingnamespace std::string_literals; //Allows the use of operator""s without having to use all of std
template <typename T>
staticinlinevoid Swap(T& a, T& b) { T temp = a; a = b; b = temp;}
template <typename T, size_t numElts>
staticvoid 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 (constauto& a : array) { std::cout << a << " "; }
std::cout << std::endl << std::endl;
ReverseArray(array);
std::cout << "after: " <<std::endl;
for (constauto& a : array) {std::cout << a << " ";}
std::cout << std::endl;
return 0;
}
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.
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?)