filter-bubble.cpp (1443B)
1 #include <algorithm> 2 #include <generator> 3 #include <memory> 4 #include <print> 5 #include <random> 6 #include <string> 7 #include <vector> 8 9 template <typename T> 10 std::generator<T&> filter_bubble(std::vector<std::weak_ptr<T>>& vec) 11 { 12 auto removed = vec.end(); 13 auto it = vec.begin(); 14 15 while (removed != it && it->expired()) 16 std::iter_swap(it, --removed); 17 18 if (it != removed) 19 { 20 auto next = std::next(it); 21 22 while (next != removed) 23 { 24 if (next->expired()) 25 { 26 std::iter_swap(next, --removed); 27 continue; 28 } 29 if (next->owner_before(*it)) 30 std::iter_swap(it, next); 31 co_yield *it->lock(); 32 it = next++; 33 } 34 35 co_yield *it->lock(); 36 } 37 38 vec.erase(removed, vec.end()); 39 co_return; 40 } 41 42 int main(int argv, char* argc[]) 43 { 44 std::vector<std::shared_ptr<std::string>> strings; 45 for (int i = 0; i < argv; ++i) 46 strings.push_back(std::make_shared<std::string>(argc[i])); 47 48 std::vector<std::weak_ptr<std::string>> string_refs; 49 std::ranges::copy(strings, std::back_inserter(string_refs)); 50 51 std::default_random_engine gen; 52 std::shuffle(string_refs.begin(), string_refs.end(), gen); 53 54 for(unsigned i = 1;;++i) 55 { 56 std::print("round {} (", i); 57 for (auto& x : filter_bubble(string_refs)) 58 std::print(" {}", x); 59 std::println(" ) {}", std::ranges::is_sorted(string_refs, std::owner_less<decltype(string_refs)::value_type>{})); 60 if (strings.empty()) 61 break; 62 strings.erase(strings.begin() + std::rand() % strings.size()); 63 } 64 }