You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中如何根据用户输入创建数组?是否改用vector?

解决动态大小数组的问题:从非标准扩展到标准方案

Hey there! Let's break down what's going on with your array code and find the right way to handle dynamic-sized collections in C++.

为什么你的代码报错,朋友的却能运行?

First off, let's talk about variable-length arrays (VLAs)—arrays where the size is set at runtime (like your friend's int px[num] where num comes from user input).

  • The C++ standard does NOT support VLAs—they're a non-standard extension that compilers like GCC happen to allow as a bonus feature. Your friend's code works because their compiler enables this extension, but if you tried it on a different compiler (like MSVC), it would fail just like your code did.
  • Your code uses const int t, but since you're assigning it a value from cin at runtime, it's a runtime constant, not a compile-time constant. C++ requires fixed array sizes to be known when the code is compiled, so this is why your code throws an error.

正确的解决方案:用std::vector

Forget about VLAs— the standard, portable, and safe way to create a dynamic-size array in C++ is to use std::vector. It's built exactly for this scenario:

  • It handles dynamic resizing automatically
  • Manages memory for you (no manual cleanup or leaks to worry about)
  • Works across all standard-compliant compilers

Here's how you'd rewrite your code with vector:

#include <iostream>
#include <vector>  // Don't forget to include this header!

int main() {
    int t;
    std::cin >> t;
    // Create a vector of doubles with size t, all initialized to 0.0
    std::vector<double> myarray(t, 0.0);
    
    // Use it just like a regular array:
    myarray[2] = 9.8;
    std::cout << myarray[2] << std::endl;
    
    return 0;
}

要不要用string?

Short answer: No. std::string is specifically designed for handling character sequences (text). It's not meant to store arbitrary types like double, so it's not a suitable replacement here.

总结

  • Avoid VLAs even if they work on your friend's compiler—they're non-standard and can break when you switch compilers or environments.
  • Stick with std::vector for dynamic arrays in C++—it's the idiomatic, safe, and portable choice.

内容的提问来源于stack exchange,提问作者Www

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:42:24