C++ 反向打印数组 任务

C++ 反向打印数组 任务,c++,C++,你将得到一个由N个整数组成的数组,你必须以相反的顺序打印这些整数 约束条件 1这里是惯用c++11中的一个解决方案,使用,这是一个可动态调整大小的容器,适用于此类应用程序 #include <vector> #include <iostream> #include <algorithm> int main() { int size; std::cin >> size; // take in the length as an inp

你将得到一个由N个整数组成的数组,你必须以相反的顺序打印这些整数

约束条件
1这里是惯用c++11中的一个解决方案,使用,这是一个可动态调整大小的容器,适用于此类应用程序

#include <vector>
#include <iostream>
#include <algorithm>

int main() {
    int size;
    std::cin >> size; // take in the length as an input

    // check that the input satisfies the requirements,
    // use the return code to indicate a problem
    if (size < 1 || size > 1000) return 1;

    std::vector<int> numbers; // initialise a vector to hold the 'array'
    numbers.reserve(size);    // reserve space for all the inputs

    for (int i = 0; i < size; i++) {
        int num;
        std::cin >> num; // take in the next number as an input

        if (num < 1 || num > 10000) return 1;

        numbers.push_back(num);
    }

    std::reverse(numbers.begin(), numbers.end()); // reverse the vector

    // print each number in the vector
    for (auto &num : numbers) {
        std::cout << num << "\n";
    }

    return 0;
}
需要注意的几点:

大多数情况下,使用名称空间std被认为是不好的做法。对于来自std名称空间的内容,请使用例如std::cin

numbers.reservesize对于正确性来说不是必需的,但是通过提前保留空间可以使程序更快

对于auto&num:numbers使用a,在c++11及更高版本中提供

您可以使for循环索引从高到低:

for (int i = N-1; i > 0; --i)
{
  std::cout << a[i] << "\n";  // Replace '\n' with space for horizontal printing.
}
std::cout << "\n";
这也适用于std::vector


使用std::vector,可以使用反向迭代器。与其他答案一样,还有其他可用的技巧

这段代码无法编译。和int a[N];反正不是标准C++。此外,您的输出循环会访问边界外的数组。我怀疑您的老师包括了其中的一个数组,尽管您没有使用它。这可能是一个关于使用什么来代替那样的数组的线索……在数组a[N]中,N是大小,而不是最后一个索引。索引的有效值为0到N-1。@BoPersson是的,谢谢你,我能找出错误。你能回答我帖子上的最后一个问题吗?你的老师应该告诉你,编写代码似乎是编程中最难的事情;但事实并非如此。调试很简单。他们应该给你一些关于如何使用调试器的基本指导。因为他们似乎没有;首先,我建议你明确地向老师寻求帮助;其次,我建议您阅读这篇文章,它不仅可以帮助您完成这项任务,还可以帮助您完成所有未来的任务。阅读cin之后,检查流失败是一个好主意
for (int i = N-1; i > 0; --i)
{
  std::cout << a[i] << "\n";  // Replace '\n' with space for horizontal printing.
}
std::cout << "\n";