std::bitset<N>::test
来自 cppreference.cn
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 位的数量 (函数模板) |
(C++20) |
检查一个数是否是 2 的整数次幂 (函数模板) |