Rust Iterator
什么是 Rust 迭代器? Rust 的迭代器(Iterator)是一种强大的抽象,它允许你遍历集合元素而不需要关心底层数据结构的具体实现。迭代器模式是函数式编程的核心概念之一,Rust 在这方面做得特别出色。 迭代器的基本概念 在 Rust 中,任何实现了 Iterator trait 的类型都可以称为迭代器: pub trait Iterator { type Item; fn next(&mut self) -> Option<Self::Item>; } 核心方法 next() 返回 Option<Item>,当迭代完成时返回 None。 创建迭代器的方法 1. iter() - 不可变引用迭代 fn main() { let vec = vec![1, 2, 3, 4, 5]; // 使用 iter() 创建迭代器 let mut iter = vec.iter(); assert_eq!(iter.next(), Some(&1)); ...
Common Algo
1. 贪心算法 (Greedy Algorithm) 核心思想: 每一步都做出局部最优选择,希望最终得到全局最优解。 适用场景: 具有「最优子结构」和「贪心选择性质」的问题。 示例:活动选择问题 #include <vector> #include <algorithm> struct Activity { int start, end; }; // 按结束时间排序 int maxActivities(std::vector<Activity>& acts) { std::sort(acts.begin(), acts.end(), [](const Activity& a, const Activity& b) { return a.end < b.end; }); int count = 1; int last_end = acts[0].end; for (...
C++ 三路比较 (Three-way Comparison)
简介 C++20 引入了三路比较运算符 <=>,也被称为"宇宙飞船运算符"(spaceship operator)。这个运算符可以一次性确定两个对象之间的所有比较关系(小于、等于、大于),大大简化了比较运算符的实现。 传统比较运算符的问题 在 C++20 之前,如果我们想为一个自定义类型实现完整的比较运算符,需要分别实现六个运算符: class Point { public: int x, y; bool operator==(const Point& other) const { return x == other.x && y == other.y; } bool operator!=(const Point& other) const { return !(*this == other); } bool operator<(const Point&...


