I have a 2D map in c++ which represents a game-field. On each field there can be a means of transport (e.g. car, plane ... (all previously defined in an enum)).
bool MainClass::isTrue(int x, int y, int w, int h)
{
for (int m = y; m < h; m++)
{
for (int n = x; n < w; n++)
{
if (map_.at(n-1).at(m-1) == SubClass::PartOfEnum::CAR ||
map_.at(n-1).at(m-1) == SubClass::PartofEnum::BOAT ||
map_.at(n-1).at(m-1) == SubClass::PartofEnum::SHIP ||
map_.at(n-1).at(m-1) == SubClass::PartofEnum::PLANE)
return (0);
}
}
return (1);
// other code ..
}
As someone can see, I'm iterating through parts of this map and want to know if on some defined coordinates there is one of those means of transport. The problem is the code inside of the for-loop which is repeating for each part of the enum. So my question is, if there is a solution for this kind of problem to write just one line of code instead of four. Maybe to save the parts of the enum in a separate variable and then take this variable for the loop. The original-enum also contains some other objects which should be not part of this loop (there are some other means of transport like bicycle in the original-enum but here only these four are relevant). Thanks in advance
So my question is, if there is a solution for this kind of problem to write just one line of code instead of four
You need four comparisons, but you don't need to access map_ more than once. A handy utility should do:
bool isVehicle(SubClass::PartOfEnum test) {
return test == SubClass::PartOfEnum::CAR ||
test == SubClass::PartofEnum::BOAT ||
test == SubClass::PartofEnum::SHIP ||
test == SubClass::PartofEnum::PLANE;
}
Which you then test against:
for (int n = x; n < w; n++)
{
if (isVehicle(map_.at(n-1).at(m-1)))
return (0);
}
A fairly straight-forward bit of refactoring. Other benefits beyond the single access is that one can tell what the condition is checking for, without delving into the details of how it's being checked. And now you can use the same condition in multiple places fairly easily, should you need to. Not to mention any update to the function will apply in all places you use it to perform the check.
One way to do it would be to use a bitmask. This is a method which turns the 4 comparisons into a 1 comparison and it might boost your performance. Say PartOfEnum is defined as follows:
enum PartOfEnum {
CAR = 1 << 0,
BOAT = 1 << 1,
SHIP = 1 << 2,
PLANE = 1 << 3,
VEHICLE = CAR | BOAT | SHIP | PLANE
};
Then the test would look like:
for (int n = x; n < w; n++)
{
if (map_.at(n-1).at(m-1) & PartOfEnum::VEHICLE)
return (0);
}
If you use an enum class though, you will need to provide the relevant operator overloads.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With