命名空间
变体
操作

std::bitset<N>::test

来自 cppreference.cn
< cpp‎ | utility‎ | bitset
 
 
 
 
bool test( std::size_t pos ) const;
(constexpr 自 C++23 起)

返回位置 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++ 标准。

DR 应用于 已发布行为 正确行为
LWG 2250 C++98 如果 pos
对应于有效的位位置,则行为未定义
在这种情况下始终抛出
异常

[编辑] 参见

访问特定位
(公共成员函数) [编辑]
(C++20)
计算无符号整数中 1 位的数量
(函数模板) [编辑]
检查数字是否为 2 的整数次幂
(函数模板) [编辑]