I know set() function for a already constructed bitset object, but I need a constructed bitset which all bits are 1. The situation is a default function parameter. for example:
void bar(std::bitset<100> flags = X) {
}
what X should be, -1 may works for first 64 bits, but not all.
bitset set() function in C++ STL bitset::set() is a built-in STL in C++ which sets the bit to a given value at a particular index. If no parameter is passed, it sets all bits to 1. If only a single parameter is passed, it sets the bit at that particular index to 1.
bitset::test() is an inbuilt function in C++ STL which tests whether the bit at a given index is set or not. Parameters: The function accepts only a single mandatory parameter index which specifies the index at which the bit is set or not. Return Value: The function returns a boolean value.
The bitset::any() is an inbuilt function in C++ STL which returns True if at least one bit is set in a number. It returns False if all the bits are not set or if the number is zero. Parameter: The function does not accepts any parameter. Return Value: The function returns a boolean value.
std::bitset<100> bs;
bs.set();
Or combine into 1 statement:
std::bitset<100> bs = std::bitset<100>().set();
In C++11:
auto bs = std::bitset<100>{}.set();
Edit: or better use std::move
to avoid copy because set
return lvalue reference bitset&
:
auto bs = std::move(std::bitset<100>{}.set());
Performance of operator ~
, flip()
and set()
:
std::bitset<100> bs;
clock_t t;
t = clock();
for(int i = 0; i < 1000000; i++) {
bs = std::bitset<100>().set();
}
t = clock() - t;
std::cout << "Using set() cost: " << t << " clicks." << std::endl;
t = clock();
for(int i = 0; i < 1000000; i++) {
bs = ~std::bitset<100>();
}
t = clock() - t;
std::cout << "Using ~ cost: " << t << " clicks." << std::endl;
t = clock();
for(int i = 0; i < 1000000; i++) {
bs = std::bitset<100>().flip();
}
t = clock() - t;
std::cout << "Using flip cost: " << t << " clicks." << std::endl;
Output:
Using set() cost: 59 clicks.
Using ~ cost: 104 clicks.
Using flip cost: 75 clicks.
Surprisingly set()
is much faster than operator ~
and flip
You can use std::bitset<100> = std::bitset<100>(std::string(100, '1'))
but it's a bit ugly imo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With