简体   繁体   中英

array copy reversal in c++

Is there a way to copy an array to another way in reverse order by using a while loop in c++?? I'm pretty sure I know how to do one with a for loop, but I'm curious if anyone knows of a way by using a while loop

Why not something like this?

#include <algorithm>

int src[] = {1, 2, 3, 4, 5};
int dst[5];

std::reverse_copy(src, src+5, dst);
int anArray = {1, 2, 3, 4, 5};
int reverseArray[5];
int count = 4;
int place = 0;
while(place < 5) {
  reverseArray[place] = anArray[count];
  count--;
  place++;
}  

As you said that you have done using for loop, you can follow following steps to convert it to while loop.

for(int i = sizeof(arr) - 1; i >= 0; i--)
{
  // your logic
}

now convert it to,

int i = sizeof(arr);
for(; i >= 0; )
{
  // your logic
  i--;
}

simply replace for with while and remove ; within the braces.

int i = sizeof(arr);
while(i >= 0)
{
  // your logic
  i--;
}

You can use std::reverse for reversing the same array and std::reverse_copy for reversing to another output array as:

int main() {
        int a[]= {1,2,3,4,5,6,7,8,9,10};
        const int size = sizeof(a)/sizeof(int);
        int b[size];

        //copying reverse to another array
        reverse_copy(a, a + size, b);
        cout << "b = {";
        copy(b, b + size, ostream_iterator<int>(cout, ", "));
        cout << "}" << endl;

        //reverse the same array
        reverse(a, a + size);
        cout << "a = {";
        copy(a, a + size, ostream_iterator<int>(cout, ", "));
        cout << "}" << endl;
        return 0;
}

Output:

b = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, }
a = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, }

Demo : http://www.ideone.com/Fe5uj

There's been a few questions similar to this recently. I wonder if it is homework or an interview question somewhere. Here's one answer:

#define ELEMENT_COUNT(a) (sizeof((a))/sizeof((a)[0]))


int anArray[] = { 1, 2, 3, 4, 5 };
int reverseArray[ELEMENT_COUNT(anArray)];
int n = ELEMENT_COUNT(anArray);
int i = 0;
while(n--)
    reverseArray[i++] = anArray[n];

I think it might be probing to see if you understand when expression like i++ and n-- are evaluated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM