當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C++ bitset count()用法及代碼示例



位元:::count()是C++中的內置STL,它以數字的二進製表示形式返回設置的位數。

用法:

int count() 

參數:該函數不接受任何參數。


返回值:該函數返回設置的位數。如果傳遞的數字是整數,它將返回數字的總數或二進製數字表示形式中的設置位數。

下麵的程序演示了bitset::count()函數。

示例1:

// CPP program to illustrate the 
// bitset::count() function 
#include <bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
    // Initialisation of a bitset 
    bitset<4> b1(string("1100")); 
    bitset<6> b2(string("001000")); 
  
    // Function to count the 
    // number of set bits in b1 
    int result1 = b1.count(); 
    cout << b1 << " has " << result1 
         << " set bit\n"; 
  
    // Function to count the 
    // number of set bits in b2 
    int result2 = b2.count(); 
    cout << b2 << " has " << result2 
         << " set bit"; 
  
    return 0; 
}
輸出:
1100 has 2 set bit
001000 has 1 set bit

示例2:

// CPP program to illustrate the 
// bitset::count() function 
// when the input is an integer 
#include <bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
    // Initialisation of a bitset 
    bitset<4> b1(16); 
    bitset<4> b2(18); 
  
    // Function to count the 
    // number of set bits in b1 
    int result1 = b1.count(); 
    cout << b1 << " has " << result1 
         << " set bit\n"; 
  
    // Function to count the 
    // number of set bits in b2 
    int result2 = b2.count(); 
    cout << b2 << " has " << result2 
         << " set bit"; 
  
    return 0; 
}
輸出:
0000 has 0 set bit
0010 has 1 set bit


相關用法


注:本文由純淨天空篩選整理自gopaldave大神的英文原創作品 bitset count() in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。