Write a program to copy the contents of one array into another in the reverse order.
/*
Program workflow:
1) User enters length of array
2) User enters elements of array, delimited by space
3) Program creates reversed array, using function reverse()
4) Program outputs reversed array
*/
#include <iostream>
#include <string>
template<class T>
T * reverse(T * array, int length) {
T * result = new T[length];
for (int i = 0; i < length; ++i) {
// fill reversed array with original array elements, starting from the end of original array
result[i] = array[length - 1 - i];
}
return result;
}
int main() {
std::cout << "Enter array length: ";
int length;
std::cin >> length;
std::string * array = new std::string[length];
std::cout << "Enter array elements, delimited by space: ";
for (int i = 0; i < length; ++i) {
std::string str;
std::cin >> str;
array[i] = str;
}
// reversed array
std::string * reversed = reverse(array, length);
std::cout << "Reversed array: ";
for (int i = 0; i < length; ++i) {
std::cout << reversed[i];
if (i < length - 1) {
std::cout << " ";
}
}
std::cout << "\n";
delete[] array;
delete[] reversed;
return 0;
}
Comments
Leave a comment