14

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.

acraig5075
  • 10,588
  • 3
  • 31
  • 50
user2729541
  • 153
  • 1
  • 1
  • 4

2 Answers2

19
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

SwiftMango
  • 15,092
  • 13
  • 71
  • 136
  • 1
    `~` requires the CPU to read, modify, write. `set` only requires a write, and they're both so fast that it actually makes a minuscule difference. – Mooing Duck Aug 29 '13 at 16:58
  • I don't think I've ever before seen code where the read made any performance difference! impressive. – Mooing Duck Aug 29 '13 at 17:04
  • 1
    @MooingDuck I just read from reference that `~` actually makes a copy of the original bitset (return `bitset` instead of `bitset&`) so that's much slower. Similar operation `flip()`, however, modifies the original bitset and return reference, but it is still slower than `set()` with smaller difference – SwiftMango Aug 29 '13 at 17:19
  • 2
    Is "bitset<100> bs = bitset<100>().set();" efficient? since it is creating a temporary bitset object with 100 bits set and then its copying the same to bs. Is my understanding correct and if so is it efficient(compared to bitset<100> bs; bs.set())? – suresh m Oct 28 '18 at 15:40
  • The Edit is not really useful as `bitset` does not benefit from move. Even if it did, it would have been done automatically in that case. – user362515 Oct 16 '21 at 07:30
  • @user362515 agree, it was already an rvalue – miles.sherman Mar 09 '23 at 22:59
7

You can use std::bitset<100> = std::bitset<100>(std::string(100, '1')) but it's a bit ugly imo

Guillaume
  • 2,044
  • 12
  • 11