Views 与惰性管道

在上一节中,我们学习了 Ranges 算法如何改善传统 STL 的使用体验。本节将深入 C++20/23 的 Views(视图)—— 一种惰性求值、零拷贝、可组合的范围适配器。通过管道操作符 |,你可以像搭积木一样组合多个 View,构建出声明式的数据处理流水线。

什么是 View

View 是 C++20 Ranges 库中的核心概念。它与容器的本质区别在于:

  • 惰性 (Lazy) —— 不会立即计算结果,只在遍历时按需求值
  • 非拥有 (Non-owning) —— 不拷贝底层数据,只是描述一种"观察方式"
  • 可组合 (Composable) —— 多个 View 可以链式叠加,形成管道

传统做法中,每一步操作都要产生中间容器:

// 传统方式:每步都生成新容器,浪费内存和时间
std::vector<int> data{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

// 第 1 步:过滤偶数 → 新容器
std::vector<int> evens;
std::copy_if(data.begin(), data.end(), std::back_inserter(evens),
             [](int n) { return n % 2 == 0; });

// 第 2 步:平方 → 又一个新容器
std::vector<int> squared;
std::transform(evens.begin(), evens.end(), std::back_inserter(squared),
               [](int n) { return n * n; });

// 第 3 步:取前 3 个 → 又一个新容器
std::vector<int> result(squared.begin(), squared.begin() + 3);

使用 View 后,一切惰性完成,零中间容器:

#include <ranges>
#include <vector>
#include <print>

std::vector<int> data{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

// View 管道:描述变换,不实际计算
auto result = data
    | std::views::filter([](int n) { return n % 2 == 0; })
    | std::views::transform([](int n) { return n * n; })
    | std::views::take(3);

// 此时没有任何计算发生!
// 遍历时才逐个元素求值:
for (int x : result) {
    std::println("{}", x);  // 输出: 4, 16, 36
}

直觉理解:View 就像一个"配方"——它描述了要对数据做什么,但不会真正动手做,直到你要求看结果(遍历)。这意味着如果你只需要前 3 个结果,它不会傻乎乎地处理全部 10 个元素。

基础 Views

标准库在 <ranges> 头文件中提供了丰富的 View 适配器。以下是最常用的几个:

views::filter — 条件过滤

保留满足谓词条件的元素:

#include <ranges>
#include <vector>
#include <print>

std::vector<int> scores{85, 42, 91, 67, 55, 78, 93, 30};

// 只保留及格分数(>= 60)
auto passing = scores | std::views::filter([](int s) {
    return s >= 60;
});

for (int s : passing) {
    std::println("{}", s);  // 85, 91, 67, 78, 93
}

views::transform — 元素变换

对每个元素施加变换函数:

#include <ranges>
#include <vector>
#include <string>
#include <print>

std::vector<std::string> names{"alice", "bob", "charlie"};

// 将每个名字首字母大写
auto capitalized = names | std::views::transform([](std::string s) {
    s[0] = std::toupper(s[0]);
    return s;
});

for (const auto& name : capitalized) {
    std::println("{}", name);  // Alice, Bob, Charlie
}

views::take 与 views::drop — 截取与跳过

#include <ranges>
#include <vector>
#include <print>

std::vector<int> nums{10, 20, 30, 40, 50, 60, 70};

// take(3):只取前 3 个
for (int x : nums | std::views::take(3)) {
    std::println("{}", x);  // 10, 20, 30
}

// drop(4):跳过前 4 个
for (int x : nums | std::views::drop(4)) {
    std::println("{}", x);  // 50, 60, 70
}

// 组合:跳过前 2 个,再取 3 个(相当于切片 [2, 5))
for (int x : nums | std::views::drop(2) | std::views::take(3)) {
    std::println("{}", x);  // 30, 40, 50
}

views::reverse — 反转顺序

#include <ranges>
#include <vector>
#include <print>

std::vector<int> nums{1, 2, 3, 4, 5};

for (int x : nums | std::views::reverse) {
    std::println("{}", x);  // 5, 4, 3, 2, 1
}

// 取最后 3 个元素(反转 → 取前 3 → 再反转)
auto last_three = nums
    | std::views::reverse
    | std::views::take(3)
    | std::views::reverse;

for (int x : last_three) {
    std::println("{}", x);  // 3, 4, 5
}

views::iota — 生成数值序列

iota 是一个"工厂 View",它不依赖已有容器,而是凭空生成数据:

#include <ranges>
#include <print>

// 无界序列:从 1 开始无限递增
// 必须配合 take 等限制使用!
for (int x : std::views::iota(1) | std::views::take(5)) {
    std::println("{}", x);  // 1, 2, 3, 4, 5
}

// 有界序列:[10, 15)
for (int x : std::views::iota(10, 15)) {
    std::println("{}", x);  // 10, 11, 12, 13, 14
}

// 实用场景:生成索引序列
auto indices = std::views::iota(0, 10);  // 0..9

注意:views::iota(1) 生成的是无限序列!如果不配合 take 或其他终止条件,对它进行遍历将导致无限循环。

管道语法 (Pipe operator |)

管道操作符 | 是 Ranges Views 最具表现力的特性。它让数据处理逻辑像自然语言一样从左到右阅读:

#include <ranges>
#include <vector>
#include <string>
#include <print>

struct Employee {
    std::string name;
    int age;
    double salary;
};

std::vector<Employee> team{
    {"Alice", 32, 95000},
    {"Bob", 28, 72000},
    {"Charlie", 45, 120000},
    {"Diana", 35, 88000},
    {"Eve", 29, 105000},
};

// 管道:从左到右读 → 过滤 → 变换 → 截取
auto top_earners = team
    | std::views::filter([](const Employee& e) {
        return e.salary > 80000;         // 留下高薪员工
    })
    | std::views::transform([](const Employee& e) {
        return std::format("{} ({})", e.name, e.age);  // 格式化输出
    })
    | std::views::take(3);               // 最多取 3 人

for (const auto& info : top_earners) {
    std::println("{}", info);
    // Alice (32)
    // Charlie (45)
    // Diana (35)
}

多行格式化提升可读性

对于复杂管道,推荐每个 View 独占一行,并对齐管道符号:

// 推荐风格:每步一行,管道符在行首
auto pipeline = data
    | std::views::filter(is_valid)
    | std::views::transform(normalize)
    | std::views::filter(above_threshold)
    | std::views::transform(format_output)
    | std::views::take(10);

// 也可以赋值给中间变量增强语义
auto valid_items   = data | std::views::filter(is_valid);
auto normalized    = valid_items | std::views::transform(normalize);
auto top_results   = normalized | std::views::take(10);

管道 vs 嵌套调用:管道语法只是语法糖。data | views::filter(f) | views::take(3) 等价于 views::take(views::filter(data, f), 3)。但管道可读性远胜嵌套调用。

C++23 新增 Views

C++23 大幅扩充了 Views 工具箱,新增了多个实用适配器:

views::zip — 多范围并行组合

将多个范围逐元素配对,类似 Python 的 zip():

#include <ranges>
#include <vector>
#include <string>
#include <print>

std::vector<std::string> names{"Alice", "Bob", "Charlie"};
std::vector<int> scores{95, 87, 92};

// zip 将两个范围逐元素配对为 tuple
for (auto [name, score] : std::views::zip(names, scores)) {
    std::println("{}: {}", name, score);
    // Alice: 95
    // Bob: 87
    // Charlie: 92
}

views::enumerate — 带索引遍历

每个元素附带其索引,告别手动维护计数器:

#include <ranges>
#include <vector>
#include <string>
#include <print>

std::vector<std::string> fruits{"apple", "banana", "cherry", "date"};

// enumerate 生成 (index, value) 对
for (auto [idx, fruit] : fruits | std::views::enumerate) {
    std::println("[{}] {}", idx, fruit);
    // [0] apple
    // [1] banana
    // [2] cherry
    // [3] date
}

views::chunk — 分组

将范围按固定大小切分为多个子范围:

#include <ranges>
#include <vector>
#include <print>

std::vector<int> data{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

// 每 3 个元素为一组
for (auto group : data | std::views::chunk(3)) {
    std::print("[ ");
    for (int x : group) {
        std::print("{} ", x);
    }
    std::println("]");
}
// 输出:
// [ 1 2 3 ]
// [ 4 5 6 ]
// [ 7 8 9 ]
// [ 10 ]

views::slide — 滑动窗口

生成连续元素的滑动窗口,适合计算移动平均等:

#include <ranges>
#include <vector>
#include <numeric>
#include <print>

std::vector<double> prices{100.0, 102.5, 98.0, 105.0, 103.0, 107.5};

// 窗口大小 3 的滑动平均
for (auto window : prices | std::views::slide(3)) {
    double avg = std::accumulate(window.begin(), window.end(), 0.0) / 3.0;
    std::println("avg = {:.1f}", avg);
}
// avg = 100.2
// avg = 101.8
// avg = 102.0
// avg = 105.2

views::join_with — 带分隔符展平

将嵌套范围展平,并在子范围之间插入分隔符:

#include <ranges>
#include <vector>
#include <string>
#include <string_view>
#include <print>

std::vector<std::string> words{"Hello", "Modern", "C++"};

// 用空格连接所有单词的字符
auto joined = words | std::views::join_with(' ');

// 转为 string 输出
std::string sentence(joined.begin(), joined.end());
std::println("{}", sentence);  // "Hello Modern C++"

views::cartesian_product — 笛卡尔积

生成多个范围的所有组合:

#include <ranges>
#include <vector>
#include <string>
#include <print>

std::vector<std::string> colors{"Red", "Blue"};
std::vector<std::string> sizes{"S", "M", "L"};

// 生成所有颜色×尺码组合
for (auto [color, size] : std::views::cartesian_product(colors, sizes)) {
    std::println("{}-{}", color, size);
}
// Red-S, Red-M, Red-L, Blue-S, Blue-M, Blue-L

编译器支持:C++23 的新 Views 在 GCC 13+、Clang 17+、MSVC 17.7+ 中已有较好支持。如果你的编译器尚未支持,可先用 range-v3 库作为替代。

Views 的特性

惰性求值 (Lazy Evaluation)

View 管道定义时不做任何计算。只有在遍历(解引用迭代器)时,才逐个元素依次通过管道中的每个步骤:

#include <ranges>
#include <vector>
#include <print>

std::vector<int> data{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

auto pipeline = data
    | std::views::filter([](int n) {
        std::println("  filter: {}", n);  // 调试:观察求值时机
        return n % 2 == 0;
    })
    | std::views::transform([](int n) {
        std::println("  transform: {}", n);
        return n * n;
    })
    | std::views::take(2);

std::println("管道已定义,但尚未执行任何操作。");
std::println("开始遍历:");

for (int x : pipeline) {
    std::println("=> {}", x);
}
// 输出顺序展示了逐元素穿越管道的过程:
// 管道已定义,但尚未执行任何操作。
// 开始遍历:
//   filter: 1        ← 不满足,跳过
//   filter: 2        ← 满足
//   transform: 2
// => 4
//   filter: 3        ← 不满足,跳过
//   filter: 4        ← 满足
//   transform: 4
// => 16
// (take(2) 已满足,停止!后续元素不再处理)

零拷贝与零分配

View 不拥有数据,也不产生中间容器。它只存储对底层数据的引用和变换描述:

std::vector<int> huge_data(1'000'000);  // 100万个元素

// 这行代码几乎不消耗内存——只是创建了一个"观察配方"
auto view = huge_data
    | std::views::filter([](int n) { return n > 0; })
    | std::views::transform([](int n) { return n * 2; })
    | std::views::take(10);

// sizeof(view) 通常只有几十到几百字节(存储 lambda 和指针)
// 而不是拷贝 100万个 int

可组合性

Views 可以无限嵌套组合,每次组合产生一个新的 View 类型:

// 你可以把常用的管道片段封装为函数
auto top_n_positive(auto&& range, int n) {
    return range
        | std::views::filter([](int x) { return x > 0; })
        | std::views::take(n);
}

// 然后继续在其结果上叠加更多 View
auto result = top_n_positive(data, 5)
    | std::views::transform([](int x) { return x * x; })
    | std::views::reverse;

Range 类别

不同的 View 会保持或降低底层范围的类别:

View 最高范围类别 说明
views::transform 保持原有类别 随机访问容器仍可随机访问
views::filter 最高为双向 无法保证随机访问(跳过元素数不确定)
views::take 保持原有类别 只是限制长度
views::reverse 要求至少双向 输入范围必须支持反向迭代
views::iota 随机访问 整数序列天然支持

生命周期陷阱:View 不拥有数据,只持有引用。如果底层容器被销毁,View 变成悬空引用。不要返回局部容器的 View!

// 错误示例:悬空引用!
auto make_view() {
    std::vector<int> local{1, 2, 3, 4, 5};
    return local | std::views::take(3);  // local 在函数返回后销毁!
}
// 使用返回的 view 是未定义行为

// 正确做法:用 ranges::to 物化为容器
auto make_vector() {
    std::vector<int> local{1, 2, 3, 4, 5};
    return local
        | std::views::take(3)
        | std::ranges::to<std::vector>();  // C++23: 物化为独立容器
}

实际管道示例

示例 1:数据清洗与排行

#include <ranges>
#include <vector>
#include <string>
#include <algorithm>
#include <print>

struct Record {
    std::string name;
    int score;
    bool active;
};

std::vector<Record> records{
    {"Alice", 92, true},
    {"Bob", -1, true},      // 无效分数
    {"Charlie", 85, false}, // 非活跃
    {"Diana", 97, true},
    {"Eve", 0, true},       // 无效分数
    {"Frank", 88, true},
    {"Grace", 91, true},
};

// 管道:过滤有效活跃记录 → 提取分数 → 取前 3 名
auto top_scores = records
    | std::views::filter([](const Record& r) {
        return r.active && r.score > 0;  // 活跃且有效
    })
    | std::views::transform([](const Record& r) {
        return std::format("{}: {}", r.name, r.score);
    })
    | std::views::take(4);

for (const auto& entry : top_scores) {
    std::println("{}", entry);
}
// Alice: 92
// Diana: 97
// Frank: 88
// Grace: 91

示例 2:生成 Fibonacci 序列

#include <ranges>
#include <print>
#include <utility>

// 利用 views::iota + transform 模拟 Fibonacci
// 方法:用 generate 思路配合 views
auto fibonacci() {
    return std::views::iota(0)
        | std::views::transform([a = 0, b = 1](int) mutable {
            int current = a;
            auto next = a + b;
            a = b;
            b = next;
            return current;
        });
}

int main() {
    // 前 10 个 Fibonacci 数
    for (int fib : fibonacci() | std::views::take(10)) {
        std::println("{}", fib);
    }
    // 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
}

提示:上面的 Fibonacci 例子使用了 mutable lambda 来维护状态。每次创建新的迭代器时状态会重置,因此多次遍历同一 view 会得到一致结果。

示例 3:文本处理管道

#include <ranges>
#include <string>
#include <string_view>
#include <print>

int main() {
    std::string csv_data =
        "Name,Score,Grade\n"
        "Alice,95,A\n"
        "Bob,87,B\n"
        ",72,C\n"              // 空名字 → 无效行
        "Diana,91,A\n"
        "Eve,,B\n";            // 空分数 → 无效行

    // 管道:按行分割 → 跳过表头 → 过滤有效行 → 提取名字
    auto names = csv_data
        | std::views::split('\n')
        | std::views::drop(1)   // 跳过表头
        | std::views::filter([](auto line) {
            // 检查行非空且首字符不是逗号(有名字)
            auto sv = std::string_view(line.begin(), line.end());
            return !sv.empty() && sv[0] != ',';
        })
        | std::views::transform([](auto line) {
            // 提取逗号前的名字部分
            auto sv = std::string_view(line.begin(), line.end());
            return sv.substr(0, sv.find(','));
        });

    for (auto name : names) {
        std::println("- {}", name);
    }
    // - Alice
    // - Bob
    // - Diana
    // - Eve
}

示例 4:与 ranges::to 结合物化

#include <ranges>
#include <vector>
#include <print>

std::vector<int> data{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

// C++23: 将 view 管道结果物化为具体容器
auto result = data
    | std::views::filter([](int n) { return n % 2 == 0; })
    | std::views::transform([](int n) { return n * n; })
    | std::ranges::to<std::vector>();  // 物化!

// result 的类型是 std::vector<int>,值为 {4, 16, 36, 64, 100}
std::println("size = {}", result.size());  // 5

本章小结

  • Views 是惰性的 —— 定义管道时不做任何计算,只在遍历时逐元素求值
  • 零拷贝、零分配 —— 不创建中间容器,只描述变换逻辑
  • 管道 | 语法 —— 从左到右阅读数据流,像流水线一样清晰
  • 基础六件套 —— filter、transform、take、drop、reverse、iota
  • C++23 扩展 —— zip、enumerate、chunk、slide、join_with、cartesian_product
  • 注意生命周期 —— View 不拥有数据,底层容器必须活得比 View 长
  • 需要物化时,使用 C++23 的 std::ranges::to<Container>()