Comparison and Coroutines

Back

Loading concept...

๐Ÿš€ Modern C++ Features: Comparison & Coroutines

Imagine youโ€™re a judge at a talent show. Before C++20, you had to write separate rules for โ€œgreater than,โ€ โ€œless than,โ€ and โ€œequal to.โ€ Now, with ONE magic wand, you can decide ALL comparisons at once!


๐ŸŽฏ The Big Picture

Think of comparing things like sorting your toy box:

  • Old Way: Check each toy one by one with many rules
  • New Way: Wave a magic wand and instantly know the order!

That magic wand? Itโ€™s called the Spaceship Operator (<=>).


๐ŸŒŸ Three-Way Comparison

What Is It?

Imagine asking: โ€œIs Apple bigger, smaller, or the same as Banana?โ€

Instead of asking THREE separate questions:

  1. Is Apple > Banana?
  2. Is Apple < Banana?
  3. Is Apple == Banana?

You ask ONE question and get ONE answer that tells you everything!

The Magic Answer Types

// Three possible answers:
// negative = "less than"
// zero     = "equal"
// positive = "greater than"

Real Life Example:

  • You have 5 candies, friend has 7
  • Three-way comparison says: โ€œYou have LESSโ€
  • One check tells the whole story!

Why This Matters

// OLD WAY - So much typing! ๐Ÿ˜ซ
bool operator<(const Toy& a, const Toy& b);
bool operator>(const Toy& a, const Toy& b);
bool operator==(const Toy& a, const Toy& b);
bool operator<=(const Toy& a, const Toy& b);
bool operator>=(const Toy& a, const Toy& b);
bool operator!=(const Toy& a, const Toy& b);

// NEW WAY - Just ONE line! ๐ŸŽ‰
auto operator<=>(const Toy& a,
                 const Toy& b) = default;

๐Ÿ›ธ The Spaceship Operator <=>

Why โ€œSpaceshipโ€?

Look at it sideways: <=> looks like a UFO! ๐Ÿ›ธ

    <=>
   /   \
  ๐Ÿ‘ฝ    ๐Ÿ‘ฝ

How It Works

#include <compare>

int a = 5;
int b = 10;

auto result = a <=> b;
// result is "less" because 5 < 10

The Three Categories

Think of comparing different things:

graph TD A["Comparison Types"] --> B["Strong Ordering"] A --> C["Weak Ordering"] A --> D["Partial Ordering"] B --> E["1 &lt; 2 &lt; 3&lt;br/&gt;Clear winner!"] C --> F["Case-insensitive&lt;br/&gt;A == a"] D --> G["NaN exists&lt;br/&gt;Some can&&#35;39;t compare"]

1. Strong Ordering ๐Ÿ’ช

Like numbered jerseys - everyone has a unique spot!

// Integers have STRONG ordering
int x = 5, y = 10;
auto r = x <=> y;
// r is std::strong_ordering::less

2. Weak Ordering ๐Ÿค

Like sorting by height - ties are allowed!

// Case-insensitive strings
// "Hello" and "HELLO" are equivalent
// but not identical

3. Partial Ordering ๐Ÿคท

Like comparing apples and oranges - sometimes you canโ€™t!

// Floating point has PARTIAL ordering
// because NaN (Not a Number) can't
// be compared to anything!
double nan = std::nan("");
auto r = nan <=> 1.0;
// r is std::partial_ordering::unordered

Your Class Gets Superpowers!

struct Student {
    std::string name;
    int score;

    // ONE line gives you ALL comparisons!
    auto operator<=>(const Student&)
        const = default;
};

// Now you can do:
Student alice{"Alice", 95};
Student bob{"Bob", 87};

if (alice > bob)  // Works!
if (alice < bob)  // Works!
if (alice == bob) // Works!
// ALL SIX operators work automatically!

๐Ÿ”„ Coroutines: Functions That Can Pause!

The Story

Imagine reading a REALLY long book:

Normal Function (Regular Reading):

  • Start at page 1
  • MUST finish the whole book
  • Canโ€™t stop until THE END
  • Others wait forever! ๐Ÿ˜ด

Coroutine (Smart Reading):

  • Read chapter 1โ€ฆ PAUSE โธ๏ธ
  • Go play outside! ๐ŸŽฎ
  • Come back, read chapter 2โ€ฆ PAUSE โธ๏ธ
  • Help mom cook! ๐Ÿณ
  • Continue where you left off!

The Three Magic Words

graph TD A["Coroutine Keywords"] --> B["co_await"] A --> C["co_yield"] A --> D["co_return"] B --> E["Wait for something"] C --> F["Give value &amp; pause"] D --> G["Finish &amp; give result"]

1. co_await - โ€œPlease Waitโ€ โณ

// Like waiting for your pizza delivery
Task<Pizza> orderDinner() {
    Pizza myPizza = co_await orderPizza();
    // Pauses here until pizza arrives!
    // Other code can run while waiting
    return myPizza;
}

Real Life:

  • You order pizza online
  • Instead of staring at the doorโ€ฆ
  • You play games while waiting!
  • Door bell rings โ†’ get pizza โ†’ continue!

2. co_yield - โ€œHereโ€™s One!โ€ ๐ŸŽ

// Like a candy dispenser
Generator<int> countTo(int n) {
    for (int i = 1; i <= n; i++) {
        co_yield i;  // Give one number
        // Pause until asked for next!
    }
}

// Usage:
for (int num : countTo(5)) {
    std::cout << num << " ";
}
// Output: 1 2 3 4 5

Real Life:

  • Vending machine gives ONE snack at a time
  • You take it, eat it
  • Come back for another!
  • Machine remembers your count!

3. co_return - โ€œIโ€™m Done!โ€ โœ…

Task<std::string> greet(std::string name) {
    co_return "Hello, " + name + "!";
}

Why Coroutines Are Amazing

BEFORE (Blocking):
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ Download File...            โ”‚
โ”‚ โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘ 60%   โ”‚
โ”‚                             โ”‚
โ”‚ [Everything else FROZEN!] โ„๏ธโ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

AFTER (Coroutines):
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ Download: โ–ˆโ–ˆโ–ˆโ–‘โ–‘โ–‘ 30%        โ”‚
โ”‚ Upload:   โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‘ 50%        โ”‚
โ”‚ Process:  โ–ˆโ–ˆโ–‘โ–‘โ–‘โ–‘ 20%        โ”‚
โ”‚ [All happening together!] ๐ŸŽ‰โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

A Complete Example

#include <coroutine>
#include <iostream>

// Simple generator
template<typename T>
struct Generator {
    struct promise_type {
        T value;

        Generator get_return_object() {
            return Generator{this};
        }
        std::suspend_always initial_suspend() {
            return {};
        }
        std::suspend_always final_suspend()
            noexcept { return {}; }
        std::suspend_always yield_value(T v) {
            value = v;
            return {};
        }
        void return_void() {}
        void unhandled_exception() {}
    };

    // Handle & iterator code...
    promise_type* promise;

    Generator(promise_type* p) : promise(p) {}
};

// Use it!
Generator<int> fibonacci(int count) {
    int a = 0, b = 1;
    for (int i = 0; i < count; i++) {
        co_yield a;
        int next = a + b;
        a = b;
        b = next;
    }
}

๐ŸŽฎ Quick Summary

Feature What It Does Likeโ€ฆ
<=> All comparisons in ONE Magic sorting hat ๐ŸŽฉ
co_await Pause & wait Ordering pizza ๐Ÿ•
co_yield Give value & pause Vending machine ๐Ÿฌ
co_return Finish coroutine โ€œThe Endโ€ ๐Ÿ“–

๐Ÿ’ก Remember This!

๐Ÿ›ธ Spaceship Operator:
   One operator to rule them all!
   <=> gives you <, >, ==, !=, <=, >= for FREE!

๐Ÿ”„ Coroutines:
   Functions that can PAUSE and RESUME!
   Like a game you can save and continue later!

๐ŸŒˆ You Did It!

You just learned:

  • โœ… Three-Way Comparison (one check tells all!)
  • โœ… Spaceship Operator (the <=> superhero)
  • โœ… Coroutines (pausable functions)

These features make C++ code:

  • Shorter (less typing!)
  • Smarter (better performance!)
  • Simpler (easier to understand!)

Now go build something amazing! ๐Ÿš€

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.