Modernes C++ programmieren

Okt 23, 2024

lst-0446-book.cpp

// https://godbolt.org/z/KxWb4q8q9 
#include <compare>  // partial_ordering etc
#include <set>
#include <iostream>
using namespace std;
struct Bruch {
  int z, n;  // zaehler / nenner
  partial_ordering operator<=>(const Bruch& re) const {
    if(n==0 || re.n==0) return partial_ordering::unordered;
    return (double)z / n <=> (double)re.z / re.n;
  }
};
int main() {
  set<Bruch> brueche{ {1,2}, {2,4}, {1,3}, {2,3}, {1,4}, {2,5}, {3,8}, {99,0} };
  for(auto b : brueche)
    cout << b.z << "/" << b.n << " ";
  cout << "\n"; // Ausgabe: 1/4 1/3 3/8 2/5 1/2 2/3
}