Jump to content

What's the best way to work with one of a number of arrays based on an integer?

- - - - -

  • Please log in to reply
2 replies to this topic

#1
Bond

Bond

    Newbie

  • Members
  • Pip
  • 5 posts
Hi, I'm new to C++, and here's the situation I need help with...

If I have three arrays (array01, array02, array03), and an integer variable will determine which array I need to work with, I can just use an "if / else if / else" set of statements to handle that.

But if I have 20 arrays, this becomes unwieldy.


So, what's the best way to set things up so that I can easily handle working with the correct array? (Obviously, the method would have to allow me to specify an index for the array in question, so I can work with the elements of it.) Would it be an array of pointers? How would I set this up?

------------------------------
Example based on the ugly method:




// These are determined elsewhere

int aNum = xxx;  

int i = yyy;



if (aNum == 1)

{

	output << array01[i];

}


elseif (aNum == 2)

{

	output << array02[i];

}


else

{

	output << array03[i];

}




#2
untitled_1

untitled_1

    Learning Programmer

  • Members
  • PipPipPip
  • 89 posts
The best I can think of is to use a 2d array. Then each row can be a different array. so you can have something like:

code:
void accessArray( aNum ){

//some stuff
output<< array[ aNUM ][i];
//other stuff

}
You wil have to make the array global though or pass pointer to function as well
that should be good. But maybe someone else has a better suggestion :)

#3
Bond

Bond

    Newbie

  • Members
  • Pip
  • 5 posts
I'll give that a shot. Thanks!




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users