反转数组中的内容 [英] Reverse Contents in Array

查看:27
本文介绍了反转数组中的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组要反转的数字.我相信我的代码中的函数是正确的,但我无法获得正确的输出.

I have an array of numbers that I am trying to reverse. I believe the function in my code is correct, but I cannot get the proper output.

输出为:10 9 8 7 6.为什么我不能得到另一半的数字?当我从计数中删除/2"时,输出显示为:10 9 8 7 6 6 7 8 9 10

The output reads: 10 9 8 7 6. Why can't I get the other half of the numbers? When I remove the "/2" from count, the output reads: 10 9 8 7 6 6 7 8 9 10

void reverse(int [], int);

int main ()
{
   const int SIZE = 10;
   int arr [SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

   reverse(arr, SIZE);
   return 0;
}
void reverse(int arr[], int count)
{
   int temp;
   for (int i = 0; i < count/2; ++i)
   {
      arr[i] = temp;
      temp = arr[count-i-1];
      arr[count-i-1] = arr[i];
      arr[i] = temp;

      cout << temp << " ";
   }
}

推荐答案

这就是我的方法:

#include <algorithm>
#include <iterator>

int main()
{
  const int SIZE = 10;
  int arr [SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  std::reverse(std::begin(arr), std::end(arr));
  ...
}

这篇关于反转数组中的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆