Can I use a boolean as an index?

1
2
3
4
5
6
7
vector<int> myvec;
myvec.resize(2);
bool idx1 = false;
bool idx2 = true;

myvec[idx1] = 123;
myvec[idx2] = 456;


Is this OK? The reason I'm asking is that I have a boolean type enum that I want to use to index a vector. I know this example doesn't make it look very elegant but it's the best solution I can think of for my code.
1
2
3
4
5
6
7
vector<int> myvec;
myvec.resize(2);
bool idx1 = false;
bool idx2 = true;

myvec[statc_cast<int>(idx1)] = 123;
myvec[statc_cast<int>(idx2)] = 456;


static_cast<int>(x) will try to cast x into an integer correctly, this makes the code obvious and not implicit, and in many cases, a lot safer (you don't actually write idx1 + 1 later on when you don't remember the type of idx1 and assume it's an integer.

static_cast<int>(true) == 1
static_cast<int>(false) == 0
I want to add that conversions true -> 1 and false -> 0 is guaranteed by standard (p. 4.7.4)
Last edited on
Yes you can. An object of type bool will be implicitly converted to type int. So there is no any problem. You need no explicitly to write static_cast as it was shown. This code is valid

myvec[idx1] = 123;
myvec[idx2] = 456;
Last edited on
Ok great, thanks :)
Topic archived. No new replies allowed.