如何根据用户设置的初始变量设置一组常量值
我的程序的输出是一个数组,该数组的大小基于用户输入。 但是为了设置数组的大小,我需要常量。如何根据用户设置的初始变量设置一组常量值
因此,一种解决方案是用户在编译/运行之前设置常量。
const int test1 = 10;
const int test2 = 20;
std::string TestArray[test1][test2];
然而除了2个常数阵列有几个更多的常量需要被设定成理想地,用户将只设置1个变量,然后将常数将根据设置上,使用像开关一样所以:
const int number = 2;
int test1a;
int test2a;
switch (number)
{
case 1:
test1a = 10;
test2a = 10;
test3a = 123;
break;
case 2:
test1a = 20;
test2a = 20;
test3a = 456;
break;
}
const int test1 = test1a;
const int test2 = test2a;
std::string TestArray[test1][test2];
test2 = 50;
但是,这给出了test1和test2在设置数组时“必须有一个常量值”的错误。但是在尝试设置test2 = 50后的行会给出错误“表达式必须是可修改的Ivalue”
正在设置的数据是建筑信息。 所以第1组将与X层,Y的人,等 2组平均酒店 第3组平均住宅楼的平均写字楼 等
那么一个解决方案是为用户之前设置的常数他们 编译/运行。
在编译时必须知道数组大小。但是,您可以使用编译时开关(使用类模板):
完整的示例:
#include <string>
template<int>
struct Switch{};
template<>
struct Switch<1>{
static constexpr int test1a = 10;
static constexpr int test2a = 10;
static constexpr int test3a = 123;
};
template<>
struct Switch<2>{
static constexpr int test1a = 20;
static constexpr int test2a = 20;
static constexpr int test3a = 456;
};
int main(){
constexpr int number = 2; //Change to 1 if you require the other.
constexpr int test1 = Switch<number>::test1a;
constexpr int test2 = Switch<number>::test1a;
std::string TestArray[test1][test2];
}
可以看出Live On Coliru
非常感谢,完美的作品! –
@SamDean,不客气。 :-) – WhiZTiM
,而不是使用固定物体的大小的数组,请尝试使用指向对象数组或指针数组的指针,则可以根据用户的输入分配内存。
int number={0};
cin >> number;
int* array{new int{number}};
但是你的代码的问题在于它更多的是C风格的编程。这可以更容易地使用std :: vector或使用类来完成。
谢谢!我会看看std :: vectors –
您介绍了手动内存管理和内存泄漏。不好。 –
不要自作聪明。我根据他的问题编写了代码,我告诉他C风格代码很糟糕。下次尝试回答问题并帮助某人。 – MIroslav
您不能在功能之外使用开关,并且无论如何您对解决方案使用了错误的方法。解决您的问题的方法是创建一个动态数组,尝试使用Google搜索并询问您之后是否有任何问题。
编辑:
#define number 2
#if number == 2
const int test2 = 10
#else
const int test2 = 20
#endif
非常感谢,经过一番简单的思考,我认为这样可以解决我的数组问题,但首先我会去解决其他常量问题。谢谢! –
你也可以尝试像这样:编辑我的答案 –
您可以使用模板,喜欢的东西:
template <std::size_t> struct config;
template <> struct config<1>
{
static constexpr int test1a = 10;
static constexpr int test2a = 10;
static constexpr int test3a = 123;
};
template <> struct config<2>
{
static constexpr int test1a = 20;
static constexpr int test2a = 20;
static constexpr int test3a = 456;
};
constexpr std::size_t number = 2;
const int test1 = config<number>::test1a;
const int test2 = config<number>::test2a;
非常感谢!你的“配置”和WhiZTiM的“Switch {}”有什么区别? “Switch似乎是一个实际的功能,”config“只是一个指针吗? –
@SamDean:'config'是一个类模板,这里没有指针,与WhiZTiM的解决方案完全一样。 –
您可以使用ternar操作:const int的TEST1 =((数== 1)10:20); –
而不是“数字== 1”我可以有“数字==变量”?然后我可以设置一个变量来设置多个常量。 –
如果变量是const,它应该没问题 –