Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,870 questions

51,793 answers

573 users

How to use bitset with _Find_first() and _Find_next() to find set bits indexes in C++

1 Answer

0 votes
#include <iostream>
#include <bitset>

int main() {
    // Create a 16-bit bitset initialized to all 0
    std::bitset<16> bs;

    // Set specific bits at positions 3, 5, 11, and 14 to 1
    bs[3] = bs[5] = bs[11] = bs[14] = 1;

    // Print the entire bitset (from highest to lowest bit)
    std::cout << std::bitset<16>(bs) << std::endl;

    // Find and print the index of the first set bit (least significant bit that is 1)
    std::cout << "First set bit at index: " << bs._Find_first() << std::endl;

    // Print all indexes of bits that are set to 1
    std::cout << "All the set bits indexes: " << std::endl;

    // Iterate through all set bits using _Find_first and _Find_next
    for (int i = bs._Find_first(); i < bs.size(); i = bs._Find_next(i)) {
        std::cout << i << " ";
    }
}



/*
run:

0100100000101000
First set bit at index: 3
All the set bits indexes: 
3 5 11 14 

*/

 



answered Nov 3, 2025 by avibootz

Related questions

1 answer 162 views
1 answer 199 views
1 answer 50 views
1 answer 40 views
1 answer 65 views
...