c++ - 反转数组中的内容

标签 c++ arrays function reverse

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

输出显示为:10 9 8 7 6。 为什么我不能得到另一半的数字?当我从计数中删除“/2”时,输出显示为: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));
  ...
}

关于c++ - 反转数组中的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19712903/

相关文章:

c++ - 如何将文本(诗歌)分成几行(字符串/字符[])并找到每一行的最后一个词

c - 如何在 O(1) 的数组中查找字符串

python - 分配给多维数组

python - 是否可以获得所有可能的网址?

c++ - 如何在c++中打印n维数组

c - 为什么编译器将变量理解为指针,而事实并非如此?

c++ for循环后自增前自增差

c++ - 在 C++ 中搜索和插入具有 3 个元素的映射

c++ - 使用 tr1 <random> 创建非均匀整数分布

java - 向右移动数组 - 作业