std::span::empty(3)

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

πŸ’… std::span::empty πŸ’…

okay bestie so this one's from the C++ Standard Libary manual (yes that's how they spell it, not me, don't come for me πŸ™ˆ) and it's genuinely so simple it's iconic. it's giving "one job, does it perfectly" energy. ✨


🌸 NAME 🌸

std::span::empty β€” literally std::span::empty, that's the whole name, we love a self-explanatory queen πŸ‘‘


✨ Synopsis ✨

[[nodiscard]] constexpr bool empty() const noexcept;  (since C++20)

Checks if the span is empty. that's it. that's the function. 🫢

quick vibe check on that signature though: [[nodiscard]] means the compiler WILL side-eye you if you call it and throw the answer away 😭, constexpr means it can happen at compile time (slay), const means it doesn't touch anything, and noexcept means it pinky-promises never to throw. main character energy all around πŸ’…

πŸŽ€ Parameters πŸŽ€

(none) β€” she takes nothing, she needs nothing. independent queen. πŸ’œ


πŸ¦‹ Return value πŸ¦‹

true if the span is empty (i.e., size() == 0); false otherwise.

no cap, that's the whole deal. size() == 0 β†’ true, anything else β†’ false. ✨


🌈 Example 🌈

// Run this code

#include <iomanip>
#include <iostream>
#include <span>

int main()
{
    std::span<const char> span{"ABCDEF"};

    while (!span.empty())
    {
        std::cout << std::quoted(span.data()) << '\n';
        span = span.last(span.size() - 1);
    }
}

ok so the way this works is SO satisfying πŸ“ β€” every loop it prints the span (quoted, because std::quoted ate πŸ’…), then shrinks from the front with span.last(span.size() - 1), and keeps going until empty() finally says "we're done here". it's a countdown but make it textual. obsessed. πŸ”₯


πŸ’€ Output πŸ’€

"ABCDEF"
"BCDEF"
"CDEF"
"DEF"
"EF"
"F"
""

look at that last "" β€” that's empty() hitting true and the loop gracefully exiting. the little empty string at the end is literally the vibe check passing. πŸ˜­πŸ’–


πŸ‘‘ See also πŸ‘‘

  • size β€” returns the number of elements in the sequence
    • (C++20) (public member function)

if empty() is the yes/no girlie, size is the one who gives you the actual receipts. they're besties fr fr. 🫢


that's the whole page bestie, no filler, no fluff, just a tiny constexpr bool doing its thing πŸ’…βœ¨

source: http://cppreference.com Β· dated 2024.06.10 Β· mwah, go write some spans πŸŽ€πŸ’–

πŸ“¦ where this page comes from