使用循环整数定义变量:c ++ [英] Using the loop integer to define variables: c++

查看:96
本文介绍了使用循环整数定义变量:c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个for循环运行 i 。对于每次迭代,我希望它创建一个变量名为 var_i ie如果我的循环运行 i = 0 i = 4 ,它应该创建如
var_0 var_1 var_2 var_3 var_4 。如何在c ++中做到这一点?

I have a for-loop which runs over i. For every iteration, I wish that it creates a variable with the name var_i i.e if my loop runs over i=0 to i=4, it should create variables like var_0, var_1, var_2, var_3 and var_4. How to do this in c++?

推荐答案

不能在编译时知道变量名。您不能在运行时创建新的变量名。

You can't, variable names must be known at compile-time. You can't create new variable names at run-time.

另一个是具有 std ::

An alternative is to have a std::map or a std::vector if your variables are continuous.

std::map<int,int> int_;
std::vector<int> vint_;
vint_.resize(5);
for ( int i = 0 ; i <= 4 ; i++ )
{
   int_[i] = i;
   vint_[i] = i;
}

您的变量将是 int_ [0] code>或 vint_ [0] 通过 int_ [4] vint_ [ 4]

这篇关于使用循环整数定义变量:c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆