I want to write a simple scan over an array. I have a std::vector<int> data
and I want to find all array indices at which the elements are less than 9 and add them to a result vector. I can write this using a branch:
for (int i = 0; i < data.size(); ++i)
if (data[i] < 9)
r.push_back(i);
This gives the correct answer but I would like to compare it to a branchless version.
Using raw arrays - and assuming that data
is an int array, length
is the number of elements in it, and r
is a result array with plenty of room - I can write something like:
int current_write_point = 0;
for (int i = 0; i < length; ++i){
r[current_write_point] = i;
current_write_point += (data[i] < 9);
}
How would I get similar behavior using a vector for data
?