L
L
LebedevImagine2019-03-25 17:07:22
C++ / C#
LebedevImagine, 2019-03-25 17:07:22

How to declare variables in a loop in c++?

The task before me is a simple task: to create several variables similar to each other with different names:
Counter1
Counter2
...
CounterN
How I imagine it:
in the for loop, declare different variables, indicating the value i in curly braces:

for (int i(1); i <= n; i++)
{
    int Counter{i} = i;
}

and at the output to receive, respectively, Counter1; counter2; counter3.
Obviously my approach to solving this problem is not working.
Then a question : how to solve the task set by me? Is it even possible? What are the alternative solutions in the absence of an adequate solution?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
nekipelov, 2019-03-25
@LebedevImagine

In C++, you cannot create variables at run time. You can do something like this:

std::vector<int> Counter;

for (int i = 0; i <= n; i++)
{
    Counter.push_back(i);
}

Or use std::map for arbitrary keys:
std::map<int, int> Counter;

for (int i = 0; i <= n; i++)
{
    Counter[i] = i;
}

A
Alexander, 2019-03-25
@alexr64

for (int i = 0; i <= n; i++)
{
    int Counter[i] = i;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question