How to concatenate the name of a variable into C++?

Asked

Viewed 473 times

1

Is it possible to concatenate the name of a variable into C++? Something like this:

using namespace std; 
int main()
{
   int casa = 10;
   string a = "ca";
   string b = "sa";
 cout << a+b << endl;

/*** console imprime int casa ***/
 /*** result console: 10 ***/

return 0;
}
  • No. They’re different variables. Maybe you get a similar effect using pointers, but not exactly this way.

  • Thanks considering for a new perspective, look at this: for (int i = 1; int < 100, int++) Cout << int(i) << Endl;

  • What you want doesn’t even make sense, say what you want, there’s another solution to this without doing what you’re asking.

  • I have 300 variables type int. And I want to print a list of it, without having to type Cout << my_int1... Cout << my_int2 300 times....

  • Take a look at the array, it might help.

  • @mrsoliver Has the answer solved your question? Do you think you can accept it? See [tour] if you don’t know how to do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site

Show 1 more comment

1 answer

3

You want to wear a array, or in C++ probably a vector will work better, so you have the variable divided into two parts, a wider variable that contains a whole collection of other variables and will have a name as you are used to. Then each of the elements within this list will be individual variables that will be accessed by their index, i.e., a sequential integer that indicates which position of the collection you are referring to.

I spoke generically about it in Difference between Std::list, Std::vector and Std:array including other ways to get a similar collation. It also has how to use the array of C, but I do not advise in C++, pretend that it does not exist, until you have advanced knowledge and then it may be that one day it will be useful.

I gave answers with examples of its use in several questions:

And have other good answers to better understand their use:

If you needed a non-integer and/or non-sequential index you would need to use a map.

  • Thank you, Maniero... I will consult your tips as you need.. as to concatenate variable names I have already solved using preprocessing....

  • You shouldn’t do this.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.