名稱空間
變體
操作

std::bitset<N>::test

來自 cppreference.com
< cpp‎ | 工具庫‎ | bitset
 
 
 
 
bool test( std::size_t pos ) const;
(C++23 起為 constexpr)

返回位置 pos 處的位的值(從 0 開始計數)。

operator[] 不同,它執行邊界檢查。

目錄

[編輯] 引數

pos - 要返回的位的位置(從 0 開始計數)

[編輯] 返回值

如果請求的位已設定,則為 true,否則為 false

[編輯] 異常

如果 pos 不對應於有效的位位置,則丟擲 std::out_of_range

[編輯] 示例

#include <bit>
#include <bitset>
#include <cassert>
#include <iostream>
#include <stdexcept>
 
int main()
{
    std::bitset<10> b1("1111010000");
 
    std::size_t idx = 0;
    while (idx < b1.size() && !b1.test(idx))
        ++idx;
 
    assert(static_cast<int>(idx) == std::countr_zero(b1.to_ulong()));
 
    if (idx < b1.size())
        std::cout << "The first set bit is at index " << idx << '\n';
    else
        std::cout << "no set bits\n";
 
    try
    {
        std::bitset<0B10'1001'1010> bad;
        if (bad.test(bad.size()))
            std::cout << "Expect unexpected!\n";
    }
    catch (std::out_of_range const& ex)
    {
        std::cout << "Exception: " << ex.what() << '\n';
    }
}

可能的輸出

The first set bit is at index 4
Exception: bitset::test: __position (which is 666) >= _Nb (which is 666)

[編輯] 缺陷報告

下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。

缺陷報告 應用於 釋出時的行為 正確的行為
LWG 2250 C++98 如果 pos
對應於有效的位位置
在這種情況下總是丟擲
異常

[編輯] 另請參閱

訪問特定位
(公共成員函式) [編輯]
(C++20)
計算無符號整數中 1 位的數量
(函式模板) [編輯]
檢查一個數是否是 2 的整數次冪
(函式模板) [編輯]