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


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


bitset::test()是C++ STL中的一個內置函數,用於測試是否設置了給定索引處的位。

用法:

bitset_name.test(index) 

參數:該函數僅接受一個強製性參數索引,該索引指定是否設置該位的索引。


返回值:該函數返回一個布爾值。如果設置了給定索引處的位,則返回true,否則返回false。

以下示例程序旨在說明上述函數:

示例1:

// CPP program to illustrate the 
// bitset::test() function 
// when bitset is a string 
#include <bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
    // Initialization of bitset 
    bitset<4> b1(string("1100")); 
    bitset<6> b2(string("010010")); 
  
    // Function to check if 2nd index bit 
    // is set or not in b1 
    if (b1.test(2)) 
        cout << "Bit at index 2 of 1100 is set\n"; 
    else
        cout << "Bit at index 2 is not set\n"; 
  
    // Function to check if 3nd index bit 
    // is set or not in b2 
    if (b2.test(3)) 
        cout << "Bit at index 3 of 010010 is set\n"; 
    else
        cout << "Bit at index 3 of 010010 is not set\n"; 
  
    return 0; 
}
輸出:
Bit at index 2 of 1100 is set
Bit at index 3 of 010010 is not set

示例2:

// CPP program to illustrate the 
// bitset::test() function 
// when the bitset is a number 
#include <bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
    // Initialization of bitset 
    bitset<4> b1(5); 
    bitset<6> b2(16); 
  
    // Function to check if 2nd index bit 
    // is set or not in b1 
    if (b1.test(2)) 
        cout << "Bit at index 2 of 5 is set\n"; 
    else
        cout << "Bit at index 2 of 5 is not set\n"; 
  
    // Function to check if 3nd index bit 
    // is set or not in b2 
    if (b2.test(3)) 
        cout << "Bit at index 3 of 16 is set\n"; 
    else
        cout << "Bit at index 3 of 16 is not set\n"; 
  
    return 0; 
}
輸出:
Bit at index 2 of 5 is set
Bit at index 3 of 16 is not set


相關用法


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