Skip to content
Related Articles

Related Articles

_Find_next() function in C++ bitset with Examples
  • Last Updated : 03 Dec, 2019

The _Find_next() is a built-in function in C++ Biteset 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:




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

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up
Recommended Articles
Page :