bit::vector
— Iterate over the Set Bits
We have methods that iterate over the elements in a bit-vector calling a function f(i)
for every index i
where the corresponding element is 1.
1constexpr void if_set_call(std::invocable<std::size_t> auto f) const;
2constexpr void reverse_if_set_call(std::invocable<std::size_t> auto f) const;
- 1
-
The iteration here is in the order
vector.first_set()
forward tovector.final_set()
. - 2
-
The iteration here is in the order
vector.final_set()
backward tovector.first_set()
.
In these methods, the f
parameter is any function taking an index as its argument. See std::invocable
. For each set element index pos
, these methods will be called f(pos)
.
Example
#include <bit/bit.h>
int main()
{
1::vector<> v(11, [&](size_t k) { return (k + 1) % 2; });
bitstd::cout << "The set indices in " << v << " are ";
2.if_set_call([](std::size_t k) { std::cout << k << ' '; });
vstd::cout << std::endl;
}
- 1
- Creates a vector of size 11 by calling a lambda that sets all the even indices.
- 2
-
The trivial print to
std::cout
lambda is called if the corresponding element inv
is set.
Output
The set indices in [1 0 1 0 1 0 1 0 1 0 1] are 0 2 4 6 8 10
See Also
vector::first_set
vector::final_set
vector::next_set
vector::prev_set