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.
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