Reputation: 341
Ok, so I'm looking for "the best way" to figure out how to deal with this.
I have booleans for a bunch of settings and want to store and access them a bit cleaner.
-- Current
bool MySetting1;
bool MySetting2;
bool MySetting3;
bool MySetting4;
.....
Accessed with
.....
if (MySetting1)
In this example, I know what my settings are called and all that fun jazz. I've thought over the options and looked around at maps and unordered maps and boolean vectors... I'm just looking for the most optimized way of doing things. Because the current way...is fine...it's just not very clean in my opinion.
enum myEnum
{
SETTING_NAME1 = 0,
SETTING_NAME2 = 0,
...
}
map<int,bool> myMap;
Is the access time doing myMap[SETTING_NAME1] the same as the current method? Is it a direct access or does it have to do a lookup?
I just wanted to update and let everyone know the strategy I took.
I used enum for identification
enum myEnum
{
SETTING_NAME1 = 0,
SETTING_NAME2 = 1,
...
}
and vector to hold and call the data
vector<bool> myVec;
if (myVec[SETTING_NAME1])
This should give me direct access, keep the size relatively small (since it's a bit based vector) as well as have the separation that I desired.
Upvotes: 2
Views: 419
Reputation: 1300
What you can do, is a bitmap
.
long long int bitmask;
or depends on how many booleans you have.
then you can do stuff like
bool checkMask(long long int bitmask, int check) { return bitmask & (1 << check) }
where check is like an index of a boolean, which can be set in an enum class
or w\e.
It's definitly not better performance than using straight booleans, but it gives you some nice ways of managing a lot of booleans.
You should check about bitmasks online, I'm sure std
has something built for this.
Upvotes: 0
Reputation: 31478
Accessing a bool directly is obviously going to be faster than accessing it via a map or anything else. However, this is unlikely to ever be performance critical and the differences are going to be negligible.
I'd advise not worrying about performance at all for something like this if it interferes one iota with writing the clearest possible code. Worrying about this is a waste of time and premature optimization for no gain. The best thing you can do is write clear, understandable code and then trust the compilers optimizer and spend your time optimizing code in performance critical areas (determined by profiling of course, not just intuition/guessing) where it will make an actual difference.
Upvotes: 5