I\'m trying to reverse an array and simultaneously store it in a new array with for
loops. I have achieved it somewhat manually but not with loops. The first code b
Since you're using C++, take advantage of the libraries it offers. Depending on whether or not you want memory-sequential access to the elements (if you're going to read it out as a string, you probably do) you could use std::vector
with reverse or alternatively a list/forward_list if contiguous access isn't an issue. std::list
has the benefit of directly offering a reverse
method.
#include
#include
using namespace std;
//int main() {
vector chars;
const char *mystr = "abcdef";
chars.reserve(6);
chars.assign(mystr, mystr+6); //assuming we don't want the null terminator.
reverse(chars.begin(), chars.end());
cout << string(&chars.front(), chars.size()) << endl;
//}
The reserve is included to maximise the performance of the copy operation.
Additionally, if mystr
was declared as a char array (or at least, pointed to writable memory) you could simply do reverse(mystr, mystr+6)
too.