首页 > 解决方案 > 如何制作数组

问题描述

我想在数组中创建 n 个元素。在第一行中我要求给出元素的数量,在第二行中我要求给出实际元素。我试过这段代码

int main() {
    int first_line;
    cin >> first_line;
    int second[first_line];
    cin>>second;
    cout<< second;


    return 0;
}

输入应该看起来像

input
       8
       1 2 3 4 5 6 7 8
output
       1 2 3 4 5 6 7 8

我需要将第二行放在整数数组中。

标签: c++

解决方案


数组(至少在 C++ 中定义)根本无法满足您的要求。

你真正要找的是 a std::vector,它做得很好。

int main() {
    int first_line;
    cin >> first_line;
    std::vector<int> second(first_line);

    for (int i=0; i<first_line; i++) {
        int temp;
        cin>>temp;
        second.push_back(temp);
    }

    for (auto i : second) {
        cout<< i << ' ';
    }
    cout << "\n";

    return 0;
}

推荐阅读