std::bitset::operator[](3)
πΈ std::bitset::operator[](3) πΈ
okay so this page is from the C++ Standard Libary manual, and itβs literally all about indexing into a std::bitset β slay π
β¨
π NAME π
std::bitset::operator[] - std::bitset::operator[]
β¨ Synopsis β¨
bool operator[]( std::size_t pos ) const; (1) (constexpr since C++11)
reference operator[]( std::size_t pos ); (2) (constexpr since C++23)
Bestie, hereβs the vibe: this accesses the bit at position pos. Version (1) returns the value of the bit, and version (2) returns an object of type std::bitset::reference that allows modification of the value. π«Ά
β οΈ Unliketest(), this does not throw exceptions: the behavior is undefined ifposis out of bounds. Not a cute look, so keepposin range, okay? π
π Parameters π
posβ position of the bit to return
π Return value π
- The value of the requested bit.
- An object of type
std::bitset::reference, which allows writing to the requested bit.
π« Exceptions π«
- (none)
π Example π
// Run this code π
#include <bitset>
#include <cstddef>
#include <iostream>
int main()
{
std::bitset<8> b1{0b00101010}; // binary literal for 42
for (std::size_t i = 0; i < b1.size(); ++i)
std::cout << "b1[" << i << "]: " << b1[i] << '\n';
b1[0] = true; // modifies the first bit through bitset::reference
std::cout << "After setting bit 0, b1 holds " << b1 << '\n';
}
Output
b1[0]: 0
b1[1]: 1
b1[2]: 0
b1[3]: 1
b1[4]: 0
b1[5]: 1
b1[6]: 0
b1[7]: 0
After setting bit 0, b1 holds 00101011
π§ Defect reports π§
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
- DR
LWG 11, applied toC++98β behavior as published: 1. the description was missing in the C++ standard; 2. there was only the non-const overload. Correct behavior: 1. description added; 2. added the const overload. πβ¨ - DR
LWG 907, applied toC++98β behavior as published: the behavior of reading the bit atposwas equivalent to that oftest(pos), buttest()may throw exceptions. Correct behavior: avoids mentioningtest(). π
π See also π
testβ accesses specific bit (public member function)
mwah π source/version: http://cppreference.com Β· date: 2024.06.10 β bye bestie, go index those bits responsibly π«Άβ¨
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms