Reputation: 1
In my case, the code I want looks something like this:
anRow0[] = {0,0,0,0,0,0,0}
anRow1[] = {0,0,0,0,0,0,0}
anRow2[] = {0,0,0,0,0,0,0}
int place(int nVar1, int nVar2) //Where nVar1 is the row and nVar2 = current turn
{
int nVert = 0;
while (anRow\i want to add nVar1 here\[nVert+1] && nVert < 6)
{
nVert += 1;
}
anRow[nVert] = nVar2;
return true;
}
I could make several "if (nVar1 == 0) //check
for anRow1[] etc. but that seems inefficient.
Is there a way to add a number like this? Also, please ignore the rest of code, I know you could for example replace the while with a for, but that's besides the point.
Appreciate any help
Upvotes: 0
Views: 661
Reputation: 87959
Seems like you want a two dimensional array, something like this
int an[3][6] = {{0,0,0,0,0,0,0}, {0,0,0,0,0,0,0}, {0,0,0,0,0,0,0}};
int place(int nVar1, int nVar2)
{
int nVert = 0;
while (nVert < 6 && an[nVar1][nVert+1])
{
nVert += 1;
}
an[nVar1][nVert] = nVar2;
return true;
}
Although that code is undoubtedly bugged (would be better with nVert < 5
). Still fixing the bugs is another question.
Upvotes: 2
Reputation: 1821
You could use a two dimensional array instead of 3 1-dimensional arrays. You can read something about them here: http://www.cplusplus.com/doc/tutorial/arrays/
Here's a possible modification:
int an[3][7] = {0};
int place(int nVar1, int nVar2) //Where nVar1 is the row and nVar2 = current turn
{
int nVert = 0;
while (anRow[nVar2][nVert+1] && nVert < 6)
{
nVert += 1;
}
anRow[nVert] = nVar2;
return true;
}
By the way, why are you are returning "true" although the return value is an int. It's allowed, but I would recommend not doing it. Return 1 instead, or change the return value to boolean.
Upvotes: 1
Reputation: 409166
You could put the arrays in another array, like this:
std::vector<int*> allRows = {
anRow0,
anRow1,
anRow2
};
Then use a variable to index the allRows
vector, like
allRows[i][nVert] = nVar2;
Or better, use an std::array
of std::array
:
std::array<std::array<int, 7>, 3> allRows = {{
{{ 0, 0, 0, 0, 0, 0, 0 }},
{{ 0, 0, 0, 0, 0, 0, 0 }},
{{ 0, 0, 0, 0, 0, 0, 0 }}
}};
Upvotes: 1
Reputation: 2909
This is not possible, since C is a compiled language and the variable names are translated to memory addresses. At run-time, the code does not even know the name of the variables in your source code.
If you want to choose a value by runtime-data, you will always have to use arrays. There are multiple options here, the best for C++ is to use some of the STL-containers (std::array, std::vector, std::list, ...), but you may also use C-style arrays.
Upvotes: 1
Reputation: 8975
No you cannot manipulate the names of variables, functions, or really anthing syntactically - if you really need this C++ is the wrong language. There may be some very limited set of functionality available by using preprocessor macros, but that is really not what you want.
Instead use containers to store your variables:
std::vector<std::array<int, 7>> rows;
Upvotes: 0