std::counte...::operator[](3)
π std::counte...::operator[](3) β std::counted_iterator::operator[]
okay bestie, welcome to the std::counte...::operator[](3) page from the C++ Standard Libary manual. Yes, that's the manual name up top β typo and all, we're keeping it π«Ά. This is the std::counted_iterator::operator[] member function, and it's giving random-access-only energy, no cap.
πΈ NAME πΈ
std::counted_iterator::operator[] β std::counted_iterator::operator[]
β¨ Synopsis β¨
here's the signature, exactly as the page shows it:
constexpr decltype(auto) operator[]( std::iter_difference_t<I> n )
const
(since C++20)
requires std::random_access_iterator<I>;
so this is a C++20 girlie π
, and the requires std::random_access_iterator<I>; line means this operator only plays when I satisfies std::random_access_iterator<I>.
okay so what does it actually do? It accesses the element at the specified relative location. The behavior is undefined if n is not less than the recorded distance to the end. That's UB, bestie β not a cute little warning, actual undefined behavior π.
π Parameters π
nβ position relative to current location
π Return value π
this->base()[n]
π Example π
// Run this code
#include <array>
#include <iostream>
#include <iterator>
#include <list>
int main()
{
std::array array{'A', 'B', 'C', 'D', 'E'};
std::counted_iterator it{array.begin() + 1, /*count:*/ 3};
for (int i{}; i != it.count(); ++i)
std::cout << it[i] << ' ';
std::cout << '\n';
for (int i{}; i != it.count(); ++i)
it[i] += ('E' - 'A');
for (int i{}; i != it.count(); ++i)
std::cout << it[i] << ' ';
std::cout << '\n';
std::list list{'X', 'Y', 'Z', 'W'};
std::counted_iterator it2{list.begin(), 3};
// char x = it2[0]; // Error: requirement `random_access_iterator` was
not satisfied.
std::cout << *it2 << '\n'; // OK
}
β Output β
B C D
F G H
X
π¦ See also π¦
operator*β accesses the pointed-to elementoperator->β (public member function)(C++20)
mwah π β cute little source/version sign-off: this page came from http://cppreference.com, it's dated 2024.06.10, and the title is std::counte...::operator[](3). periodt. π
π¦ 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