std::span::last(3)

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

πŸ’– std::span::last(3) πŸ’–

okay bestie, welcome to the C++ Standard Libary page for std::span::last β€” yes, β€œLibary” is canon in the header, we’re leaving it iconic πŸ’…. This is the whole vibe: grabbing a view of the last Count elements of a span. No cap, it’s giving β€œtail of the group chat” energy.

πŸ’– NAME πŸ’–

std::span::last β€” std::span::last

Yes, that’s literally the name. The function is std::span::last, and this page is about… std::span::last. Redundant? Maybe. Iconic? Absolutely. πŸ‘‘

🌸 Synopsis 🌸

Here are the overloads, bestie β€” both since C++20:

          template< std::size_t Count >
       (1) (since C++20)
          constexpr std::span<element_type, Count> last() const;
          constexpr std::span<element_type, std::dynamic_extent> last(
       (2) (since C++20)
          size_type Count ) const;

So what’s the tea? last() obtains a span that is a view over the last Count elements of this span. 🫢

🚨 if Count > Extent, the program is ill-formed β€” not a vibe. And if Count > size(), the behavior is undefined. So maybe don’t test fate, fr fr. πŸ’€

πŸŽ€ Return value πŸŽ€

You get a span r that is a view over the last Count elements of *this, such that:

r.data() == this->data() + (this->size() - Count) && r.size() == Count

That’s the exact contract, no cap. ✨

πŸ¦‹ Example πŸ¦‹

Run this code, bestie:

       // Run this code

        #include <iostream>
        #include <span>
        #include <string_view>

        void println(std::string_view const title, auto const& container)
        {
            std::cout << title << '[' << std::size(container) << "]{ ";
            for (auto const& elem : container)
                std::cout << elem << ", ";
            std::cout << "};\n";
        };

        void run(std::span<const int> span)
        {
            println("span: ", span);

            std::span<const int, 3> span_last = span.last<3>();
            println("span.last<3>(): ", span_last);

            std::span<const int, std::dynamic_extent> span_last_dynamic =
       span.last(2);
            println("span.last(2): ", span_last_dynamic);
        }

        int main()
        {
            int a[8]{1, 2, 3, 4, 5, 6, 7, 8};
            println("int a", a);
            run(a);
        }

πŸ’» Output: πŸ’»

It prints exactly this:

int a[8]{ 1, 2, 3, 4, 5, 6, 7, 8, };
span: [8]{ 1, 2, 3, 4, 5, 6, 7, 8, };
span.last<3>(): [3]{ 6, 7, 8, };
span.last(2): [2]{ 7, 8, };

πŸ‘‘ See also πŸ‘‘

  • first β€” obtains a subspan consisting of the first N elements of the sequence (public member function)
  • subspan β€” obtains a subspan (public member function)

that’s the whole page, bestie πŸ’– β€” source: http://cppreference.com Β· date: 2024.06.10 Β· page: std::span::last(3) Β· now go take the last() of something cute ✨

πŸ“¦ where this page comes from