Open In App

_Find_next() function in C++ bitset with Examples

Improve
Improve
Like Article
Like
Save
Share
Report

The _Find_next() is a built-in function in C++ Bitset class which returns an integer which refers the position of next set bit in bitset after index. If there isn’t any set bit after index, _Find_next(index) will return the size of the bitset. Syntax:

iterator bitset._Find_next(index)
           or
int bitset._Find_next(index)

Parameters: The function accepts one mandatory parameter index which specifies the index after which the first set bit is to be found in the bitset. Return Value: The function returns an integer which refers to the position of next set bit in bitset after specified index. If there isn’t any set bit after index(the specified index), _Find_next(index) will return the size of the bitset. Below is the illustration of the above function: Example: 

CPP




// C++ program for illustration
// of _Find_next() function
 
#include <bits/stdc++.h>
using namespace std;
 
#define M 32
 
int main()
{
    // default constructor initializes with all bits 0
    bitset<M> bset;
    bitset<M> bset1;
    bitset<M> bset2;
 
    // 00000000000000000000000000100000
    bset[5] = 1;
 
    // 00000000000000000000010000100000
    bset[10] = 1;
 
    // 01000000000000100001000000000001
    bset1[0] = bset1[12] = bset1[17] = bset1[30] = 1;
 
    // function returns the next set bit
    // in bitset after index 0
    cout << "Next set bit after index 0 in bset\n";
    cout << bset._Find_next(0) << "\n";
 
    // function returns the next set bit
    // in bitset after index 6
    cout << "Next set bit after index 6 in bset\n";
    cout << bset._Find_next(6) << "\n";
 
    // finds all set bits in bitset bset1
    cout << "Find all set bits in bset1\n";
    for (int i = bset1._Find_first();
         i < bset1.size();
         i = bset1._Find_next(i))
        cout << i << " ";
    cout << "\n";
 
    // function returns bset2.size()
    // when there isn't any set bit after index
    cout << "Next set bit after index 5 in bset2\n";
    cout << bset2._Find_next(5) << "\n";
 
    return 0;
}


Output:

Next set bit after index 0 in bset
5
Next set bit after index 6 in bset
10
Find all set bits in bset1
0 12 17 30 
Next set bit after index 5 in bset2
32

Reference: https://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-3.4/bitset-source.html



Last Updated : 22 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads