Skip to main content
gamedev.net
🔒 Locked

Multiple comparisons

Started by Iccarus Jan 30, 2006 at 7:39 PM 3 replies 550+ views
Original Post
Iccarus
Iccarus
If I want to compare an integer to multiple different ones is it possible to do this without having a long if statement with multiple ors? I want to compare: newroom->GetType() to 4,6,7,8,9,13,14,15 and if it matches any of them do one thing, if it doesn't do another. Is it possible without

if (newroom->GetType() == 4 || newroom->GetType() == 6...)
Unless I say otherwise assume I'm talking bout c++. Make things a lot easier :D
mother
mother
switch (newroom->GetType()){case 4:case 6:case 7:case 8:case 9:case 13:case 14:case 15:    // do one thing    break;default:    // do another    break;};
Morpheus011
Morpheus011
One simple solution that I can see off the top of my head is to make a static array of the values you are checking against

i.e. int array[ARRAY_SIZE] = {your values here};

and then simply have a for loop

for (int i = 0; i < ARRAY_SIZE; i++)
{
if (newroom->GetType() == array)
do what you want here
}

hope that helps
M2tM
M2tM
You could write a comparison function... Something like:
bool stoi(string d, int& r) {	r = 0;	for(int i = 0;d >= '0' && d <='9' && i<d.length();i++) {		r = (r * 10) + (d - '0');	}	return i==d.length();}//if val equals any one of the ints then 1 is returned.  If not, 0 is returned.bool orEquals(int val, string ints){	string tmp;	int i = 0;	int curInt;	if(ints.length()==0){return 0;}	while(i<ints.length()){		tmp = "";		for(;ints!=','&&i<ints.length();i++){			tmp+=ints;		}		if(!stoi(tmp.c_str(), curInt)){return 0;}		if(val==curInt){return 1;}		i++;	}	return 0;}bool andEquals(int val, string ints){	string tmp;	int i = 0;	int curInt;	if(ints.length()==0){return 0;}	while(i<ints.length()){		tmp = "";		for(;ints!=','&&i<ints.length();i++){			tmp+=ints;		}		if(!stoi(tmp.c_str(), curInt)){return 0;}		if(val!=curInt){return 0;}		i++;	}	return 1;}


and then you call the function like this:

orEquals(newroom->GetType(), "4,6");

If GetType returned a 4 or a 6 then equalTo would return a 1.

if you want to simulate the a==b && a==c type thing then I have an andEquals function as well.
_____"You're using a screwdriver to nail some glue to a ming vase. " -ToohrVyk
Iccarus
Iccarus
Thanks mother (lol, nice name :D) it worked.
Unless I say otherwise assume I'm talking bout c++. Make things a lot easier :D

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.