std::counte...::operator[](3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

πŸ’– 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 element
  • operator-> β€” (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