【问题标题】:Reversing order of integers in an Array反转数组中整数的顺序
【发布时间】:2017-04-15 18:13:29
【问题描述】:

我在下面遇到了这个问题。我正在尝试完成一个程序,该程序从用户读取多个输入以形成一个数组,然后以相反的顺序输出该数组。

输入 n 的第一行应该是数组中的整数个数。下一个输入应该是数组中每个索引的值。

我第一次在 C++ 中使用数组并发现这令人困惑,我搜索并发现有一种方法可以在一行中完成此操作,但我想在没有它的情况下完成此操作。我在当前循环上尝试了 if 语句和 for 循环,但每次我最终都会过度复杂化并且无处可去。我确定我缺少一种简单的方法。

示例输入 -

4

1 2 3 4

输出应该是 -

4 3 2 1

#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <string>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <unordered_map>

using namespace std;


int main(){
    int n;
    cin >> n;
    vector<int> arr(n);
    for(int arr_i = 0;arr_i < n;arr_i++){
       int* arr = new int[n];
       cin >> arr[arr_i];      
    }

    return 0;
}

【问题讨论】:

  • 包含很多内容。您可以使用vectoriostream。提高可读性并减少编译器的工作量。

标签: c++ arrays integer


【解决方案1】:

您可以使用&lt;algorithm&gt; 中的std::reverse() 函数,如本文档中所述:http://www.cplusplus.com/reference/algorithm/reverse/

std::reverse(arr.begin(), arr.end());

如果你不需要反转你的向量,而只是以相反的顺序打印,你也可以反向迭代它:

for (std::vector<int>::const_reverse_iterator it = arr.rbegin(); it != arr.rend(); ++it)
    std::cout << *it << " ";

警告:小心你的行int* arr = new int[n];,这似乎是内存泄漏。这隐藏了数组arr 的真实符号,然后您的局部变量arr 就会丢失。您应该删除此行。

【讨论】:

    【解决方案2】:

    我认为这是您可以对当前代码进行的最小修改以使其正常工作。请注意,您不需要在 for 循环主体中分配新的 arr,因为您已经有一个具有该名称的向量。

    int main(){
        int n;
        cin >> n;
        vector<int> arr(n);
        for(int arr_i = 0; arr_i < n; arr_i++){
           cin >> arr[n-arr_i-1];
        }
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2011-07-21
      • 2016-02-27
      • 2019-06-25
      • 1970-01-01
      • 2023-03-05
      • 2023-04-02
      • 2016-01-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多