std::bitset<N>::test
来自cppreference.com
                    
                                        
                    
                    
                                                            
                    |   bool test( std::size_t pos ) const;  | 
(C++23 前) | |
|   constexpr bool test( std::size_t pos ) const;  | 
(C++23 起) | |
返回位于位置 pos 的位的值。
不同于 operator[] ,它进行边界检查,且若 pos 不对应 bitset 中的合法位置则抛出 std::out_of_range 。
参数
| pos | - | 要返回的位的位置 | 
返回值
若所求位被设置则为 true ,否则为 false 。
异常
若 pos 不对应 bitset 中的合法位置则抛出 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 << "first set bit 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'; } }
可能的输出:
first set bit at index 4 Exception: bitset::test: __position (which is 666) >= _Nb (which is 666)
参阅
|    访问指定的位  (公开成员函数)  | |
|    (C++20)  | 
   计量无符号整数中为 1 的位的数量   (函数模板)  | 
|    (C++20)  | 
  检查一个数是否为二的整数次幂  (函数模板)  |