首页 > 解决方案 > 数组的存储大小未知

问题描述

我想创建程序来反转数组。但是我收到一个错误,即数组a[]的存储大小未知。

#include<iostream>
using namespace std;

int main()
{
    int a[];
    int b, c;
    cin >> b;
    for (int i = 0; i < b; i++)
        cin >> a[i];
    for (c = b; c >= 0; c--)
        cout << a[c] << endl;

    return 0;
}

标签: c++arraysalgorithmc++11reverse

解决方案


我想创建程序来反转数组

只需使用std::vector即可。

一个好的开始是:

#include <iostream>
#include <vector>

int main()
{
    std::size_t size;
    std::cin >> size;        // size of the array    
    std::vector<int> a(size);// allocate memory for provided size and 
                             // initialize with 0's
    // using range based loop iterate though referances of
    // each elements in the array and update with user input.
    for (int& element : a) std::cin >> element;

    return 0;
}

推荐阅读