creating & assigning variables automatically ?

Hi,

I have create a simple grid represented by 3 horizontal lines, and 3 vertical lines. This effectively makes 16 "squares".

Now, when something occurs in one of these squares, I tell my software to do something specific.

However the only way I have found to identify these squares is to do it individually.

such as:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Bool Grid0 = false;
Bool Grid1 = false;
......
Bool Grid16 = false;
int dx, dy; //coordinates

	if (dx<200 && dy<200){
		grid0=true;
	}


	if (dx<400 && dx>=200 && dy<200)
	{
		grid1=true;
	}

	if (dx<200 && dy<400 && dy>=200)
	{
		grid2=true;
	}

		if (dx<400 && dx>=200 && dy<400 && dy>=200)
	{
		grid3=true;
	}

....up to grid 16, if I am not to old to type more code


Now would it be possible to do the following:

1
2
3
4
5
6
7
8
9
10
11
int Z=0;

for (x=0; x<17; x++){
	if (dx<200 && dy<200)
	{
	//create variable "bool gridZ
	}
	Z=Z+1
	dx=dx+200;
	dy=dy+200;
                               }


This obviously would work only up to grid4, but I hope you got my point.

How can I do that ?

Would really have if you give me some feedback guys,

Regards,

Wissam

Last edited on
Yes, there's a way to do what you want to do, but it's not as simple as some keyword that dynamically creates a new variable by some name.

Assuming your grid isn't going to ridiculously large, I would recommend you take a look at std::vector<>s. Here's a few links that should help you out:

http://cplusplus.com/reference/stl/vector/
http://cplusplus.com/reference/stl/vector/push_back/
http://cplusplus.com/reference/stl/vector/at/

Their main advantage over arrays is that they're expandable, and for your project they seem to fit the bill perfectly. They're class templates, so you'll need to put bool in between the <>s to make them work.

Happy coding! :)

-Albatross
Last edited on
And by using vector your first lines of having to assign false to all your values becomes as simple as:
1
2
std::vector<bool> grid;
grid.assign(16, false);
Or std::vector<bool> grid(16);, for that matter.
Topic archived. No new replies allowed.