std::bitset<N>::test
ja.cppreference.net より
bool test( std::size_t pos ) const;
|
(C++23 から constexpr) | |
位置 pos のビットの値を返します(0から数えます)。
operator[] とは異なり、範囲チェックを行います。
パラメータ
| pos | - | 返されるビットの位置(0から数える) |
戻り値
true 要求されたビットが設定されている場合、 false それ以外の場合。
例外
std::out_of_range がスローされる条件は、 pos が有効なビット位置に対応していない場合です。
例
このコードを実行
#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
ビット数をカウント
(関数テンプレート) |
|
(C++20)
|
数値が
2
の整数乗かどうかをチェック
(関数テンプレート) |