I need to interface between two pieces of code: one which outputs an "array" (I may accept output as either a "standard" C++
array (of type double), or a std::vector<double>
), and one which takes in a std::bitset
.
Putting aside what goes on at either end...
What is most efficient (time-wise) way to convert the output array to a std::bitset
, according to some function?
By this I mean, for each element in the output bitset, I want to assign a value (0
or 1
) according to some function (e.g., elements greater than N
are assigned a value of 1
, elements less than N
are assigned a value of 0
... or all even elements are assigned a value of 1
, etc).
The obvious (and, perhaps, simplest) method is, of course, to use a loop. E.g., something like (in the case of value comparison):
L = outputVector.size();
std::bitset<L> inputBitset;
for(int i = 0; i < L; ++i){
if(outputVector[i] > N){
inputBitset[i] == 1;
}
}
I've also considered doing something with std::replace_if()
(e.g., replacing all values greater than N
with a 1
, then iterating over the "array" afterwards and setting bits accordingly), which may offer a speed improvement (although it seems incredibly clunky).
Where speed is the only thing I'm concerned about, is there a better way?
The most likely pattern that your compiler will be able to vectorize is simply setting the result to comparison result directly
for (int i = 0; i < L; ++i)
inputBitset[i] = outputVector[i] > N;
Such loops will generally be vectorized if your processor supports it. More complex loops may also be vectorized, so would end up with the same result, but there's no reason to make the code more complex than it needs to be.