【问题标题】:How do I create a C++ Integer Array of constant length?如何创建恒定长度的 C++ 整数数组?
【发布时间】:2019-09-09 11:54:32
【问题描述】:

我是一位经验丰富的 Python 程序员,正在尝试学习 C++。我在初始化固定大小的整数数组时遇到问题。

我已阅读this,但将我的整数创建为常量并没有解决我的问题。我在这里错过了什么?

顺便说一句,我正在使用 VS2019 社区,任何帮助将不胜感激!

#include <iostream> 
#include <sstream> 

int numericStringLength(int input) {

    int length = 1;

    if (input > 0) {
        // we count how many times it can be divided by 10:
        // (how many times we can cut off the last digit until we end up with 0)
        for (length = 0; input > 0; length++) {
            input = input / 10;
        }
    }

    return length;

}

int convertNumericStringtoInt(std::string numericString) {

    std::stringstream data(numericString);
    int convertedData = 0;
    data >> convertedData;

    return convertedData;

}


int main() {

    std::string numericString;

    std::cout << "Enter the string: ";
    std::cin >> numericString;

    const int length = numericStringLength(convertNumericStringtoInt(numericString));

    std::cout << "Length of Numeric string: " << length << "\n";

    int storage[length];
}

【问题讨论】:

  • 你可以使用std::array&lt;int, size_you_want_ie_20&gt; my_array
  • 使用std::vector&lt;int&gt;,除非你有充分的理由不这样做。
  • @nada 问题是在编译时不知道大小,这是std::array所必需的。
  • @Shawn 有答案时使用答案部分
  • 你也一样@nada

标签: c++ arrays


【解决方案1】:

但是将我的整数创建为常量并没有解决我的问题

数组长度为const 是不够的。它必须是编译时间常量。 const 仅仅意味着对象在其整个生命周期内都不会改变 - 即它意味着运行时常量。由于length 不是编译时间常数,因此程序格式错误。编译时常量值示例:

  • 文字,例如 42
  • 模板参数
  • 枚举
  • constexpr变量
  • const 带有编译时常量初始化器的变量(这可能有一些限制,我不确定)

从程序中应该很清楚,长度是根据用户输入计算的,这在程序编译时是不可能做到的。因此,由于您无法将其设为编译时间常数,因此您无法使用数组变量。您需要动态分配数组。最简单的解决方案是使用向量:

std::vector<int> storage(length);

【讨论】:

    【解决方案2】:

    创建变量const 是不够的。

    • const 仅表示“初始化后我不会更改它”。

    它必须是一个编译时间常量,因为基本 C 数组的机制已被烘焙到构成可执行文件的计算机指令中。

    • 您是在运行时计算它,所以没有办法工作。

    您将不得不使用向量或其他一些此类可动态调整大小的数组类型。

    【讨论】:

      【解决方案3】:

      如果你想要一个固定大小的数组,可以使用std::array,例如:

      std::array<int, 3> arr { 1,2,3 };
      //              ^
      //          fixed size needs to be known at compile time
      

      如果编译时不知道大小,请使用std::vector

      【讨论】:

        【解决方案4】:

        您遇到的问题是length 是一个运行时 常量,它的值是在程序运行时计算的。这与 compile-time 常量相反,编译器在构建程序时知道其值。

        数组的大小需要编译时常量。

        如果大小在编译时未知,而仅在运行时未知,则应使用std::vector

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-08-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-11-23
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多