首页 > 解决方案 > 如何创建恒定长度的 C++ 整数数组?

问题描述

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

我已阅读内容,但将整数创建为常量并没有解决我的问题。我在这里想念什么?

顺便说一句,我正在使用 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];
}

标签: c++arrays

解决方案


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

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

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

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

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

推荐阅读