[英]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++?? 有没有一种方法可以通过使用c ++中的while循环以相反的顺序将数组复制到另一种方法? 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
我很确定我知道如何使用for循环,但是我很好奇是否有人知道使用while循环的方法
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
循环一样,您可以按照以下步骤将其转换为while
循环。
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 ;
只需将其替换
for
while
并删除即可;
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: 您可以使用
std::reverse
来反转相同的数组,而使用std::reverse_copy
来反转到另一个输出数组,如下所示:
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 演示: 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. 我认为可能正在探究是否了解对i ++和n--之类的表达式进行评估的时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.