1.11M Members

Create new variables with a loop?

 
0
 

I need a way to concurrently create variables with a loop.

Like... Instead of

int my_var_1 = 1;
int my_var_2 = 1;
int my_var_3 = 1;

Because the user may need thousands of variables, and I don't want there to be a limit. So I was wondering if there was a way to declare variables with a loop appending a number to the end of the name.

Something like the following:

for(int i=1; i<3; i++) {
int my_var_ + i = 1;
}

This in theory would create three integers named my_var_1, my_var_2, and my_var_3, and set the value of them all to 1.

Can I do something like this?

 
0
 

Can't u use an array?

#include <iostream>
using namespace std;
main()
{
short variable_number;
cin >> variable_number;
int *my_var = new int[variable_number];
for(int i = 0; i< variable_number; i++)
{
my_var[i] = 1;
}
return 0;
}
 
0
 

Ah, okay.. Thanks.

 
0
 

Can't u use an array?

#include <iostream>
using namespace std;
main()
{
short variable_number;
cin >> variable_number;
int *my_var = new int[variable_number];
for(int i = 0; i< variable_number; i++)
{
my_var[i] = 1;
}
return 0;
}

To be a little pedantic, that code has the potential to leak memory, so you should be careful. Every new should have a delete to go with it, so the snippet should be:

#include <iostream>

int main()
{
   short variable_number;
   std::cin >> variable_number;

   int *my_var = new int[variable_number];
   for(int i = 0; i< variable_number; i++)
      my_var[i] = 1;

   // Do things with the array
   
   delete[] my_var;   // Free the memory that we used for the array when it's no longer needed
   
   return 0;
}

Even better, use std::vector instead:

#include <iostream>
#include <vector>

int main()
{
   short variable_number;
   std::cin >> variable_number;

   std::vector< int > my_var(variable_number);
   for(int i = 0; i< variable_number; i++)
      my_var[i] = 1;
   
   return 0;
}

This way, the memory management is taken care of for you.

There are people who say that you should learn to use arrays properly before you start with std::vector , and they've probably got a point, but at the end of the day the slight overhead is better than a bunch of memory leaks :o)

 
0
 

Haha, I forgot the delete[]
Nvm, thx for the correction.(I had a long day trying to solve my problem and I write it while reading another website)

You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: