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<
You can't create variables at runtime. Use std:vector
instead so you'll get var[0]
, var[1]
, etc.
You can't, variable names must be known at compile-time. You can't create new variable names at run-time.
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;
}
Your variables would be int_[0]
or vint_[0]
through int_[4]
or vint_[4]
.
You can also use an array of the required size and initialize it with a default value in the loop
int var[4];
for(int i=0; i < 4; i++){
var[i] = 0;
}