c++ - 如何创建恒定长度的 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];
}
解决方案
但是将我的整数创建为常量并没有解决我的问题
数组长度为 是不够的const
。它必须是编译时间常数。const
仅仅意味着对象在其整个生命周期内都不会改变 - 即它意味着运行时常量。由于length
不是编译时间常数,因此程序格式错误。编译时间常数值的示例:
- 42等字面量
- 模板参数
- 枚举
constexpr
变量const
带有编译时常量初始化器的变量(这可能有一些限制,我不确定)
从程序中应该很清楚,长度是根据用户输入计算的,这在程序编译时是不可能做到的。因此,由于您无法将其设为编译时间常数,因此您无法使用数组变量。您需要动态分配数组。最简单的解决方案是使用向量:
std::vector<int> storage(length);
推荐阅读
- python - 如何在更新函数代码后第二次从另一个脚本导入函数
- xcode - NSComboBox 使用 NSValueTransformer 自动完成
- python - Python 3.X:如何调用类的函数来检查输入字符串的特征?
- python - 将深度嵌套的字典转换为熊猫数据框?
- android - 如何保持我的 Android VideoView 的纵横比仅与其高度成比例?
- r - 如何从 R 包中的函数生成 html / pdf 报告
- azure - 使用 helm 从 ACR 中拉取容器
- powershell - 如何处理使用powershell比较现有文件的if语句?
- azure-storage - 每个文件单独的 SharedAccessFilePolicy 可以吗?
- pytorch - 在 torch.sparse_coo_tensor(indices, values, size=None, dtype=None, device=None, requires_grad=False) 的输出中,nnz 是什么意思?