I’m new to c++.
I’d like to have an const array of a certain length. It is a rather long array so the standard method for initializing constant arrays, namely:
const bool some_array[] = {true, false, true};
is impractical. I’d like to initialize a constant array of boolean values. I’ve tried to implement it like this:
bool* sieve_of_eratosthenes(bool* n, n_length);
int main(){
bool b[500];
bool primeList[] = {sieve_of_eratosthenes(b, 500)};
}
this almost works, though it isn’t very elegant or space-efficient (i’d be open to comments on how better implement this array). The trouble is, the zeroth element of the returned array, i.e. primeList, is set to true/1, even though I’ve explicitly set the zeroth element in the boolean array returned by my s_of_e() function to false/zero.
primeList[0] == 1
when it should be:
primeList[0] == 0
since 0 isn’t prime…
Can anyone enlighten me as to why it’s doing this?
Your code,
doesn’t work because
the function returns a pointer, not an array, and
even if the function returned a reference to an array, that would decay into a pointer in its use in the initializer list.
(Also it should not compile because implicit
inthas never been part of C++.)The pointer is converted to
bool, and that’s the only element your array gets.Instead, do this:
Note however that
std::vectoris designed to optimize the case ofboolelements, with an ordinary C++ implementation using just 1 bit per element.That can be seen as a feature or as a design level bug, depending on one’s view.