实战:数据处理管道
本章是卷二的综合实战。我们将把前六章学到的所有技术——vector、map、Lambda、Ranges、Views、optional——融合到一个完整的 CSV 数据处理工具中。整个程序实现"读取 → 解析 → 过滤 → 转换 → 聚合 → 格式化输出"的完整管道。
1. 项目目标
我们要构建一个销售数据分析工具,处理如下 CSV 格式的输入:
name,region,category,amount,quantity
张伟,华东,电子产品,12500.00,3
李娜,华北,家居用品,8900.50,7
王强,华南,电子产品,23000.00,5
赵敏,华东,食品饮料,4500.00,12
陈刚,华北,电子产品,18700.00,4
刘洋,华南,家居用品,6200.00,9
周芳,华东,食品饮料,3200.00,15
吴磊,华北,食品饮料,5100.00,8
孙悦,华南,电子产品,31000.00,2
马超,华东,家居用品,11500.00,6
处理管道包含以下阶段:
- 解析:将 CSV 文本行转换为结构化记录
- 过滤:去掉无效记录,按条件筛选
- 转换:计算派生字段(如单价、评级)
- 聚合:按区域/品类分组统计
- 输出:格式化表格打印结果
用到的卷二技术:std::vector(2.1)、std::map(2.2)、Lambda 表达式(2.3)、ranges::sort / min / max(2.4)、views::filter / transform / split(2.5)、std::optional(2.6)。这是一个真正的"串珠"项目。
2. 数据模型
首先定义数据记录结构和必要的头文件:
#include <algorithm>
#include <charconv>
#include <format>
#include <fstream>
#include <iostream>
#include <map>
#include <numeric>
#include <optional>
#include <ranges>
#include <string>
#include <string_view>
#include <vector>
// 销售记录
struct Record {
std::string name; // 销售人员
std::string region; // 区域
std::string category; // 产品品类
double amount; // 金额
int quantity; // 数量
// 计算单价
double unit_price() const {
return quantity > 0 ? amount / quantity : 0.0;
}
};
// 评级:根据金额划分
enum class Rating { Bronze, Silver, Gold, Platinum };
std::string_view rating_label(Rating r) {
switch (r) {
case Rating::Bronze: return "铜牌";
case Rating::Silver: return "银牌";
case Rating::Gold: return "金牌";
case Rating::Platinum: return "白金";
}
return "未知";
}
Rating compute_rating(double amount) {
if (amount >= 25000) return Rating::Platinum;
if (amount >= 15000) return Rating::Gold;
if (amount >= 8000) return Rating::Silver;
return Rating::Bronze;
}
这里 Record 用聚合结构体,简洁明了。unit_price() 是一个派生计算,后面管道会用到。
3. 解析层
CSV 解析是整个管道的入口。我们使用 views::split 拆分字段,并用 std::from_chars 做数值转换。返回 std::optional<Record> 表达"可能解析失败":
// 去除字符串首尾空白
std::string trim(std::string_view sv) {
auto start = sv.find_first_not_of(" \t\r\n");
if (start == std::string_view::npos) return "";
auto end = sv.find_last_not_of(" \t\r\n");
return std::string(sv.substr(start, end - start + 1));
}
// 安全解析 double
std::optional<double> parse_double(std::string_view sv) {
double value{};
auto [ptr, ec] = std::from_chars(sv.data(), sv.data() + sv.size(), value);
if (ec != std::errc{}) return std::nullopt;
return value;
}
// 安全解析 int
std::optional<int> parse_int(std::string_view sv) {
int value{};
auto [ptr, ec] = std::from_chars(sv.data(), sv.data() + sv.size(), value);
if (ec != std::errc{}) return std::nullopt;
return value;
}
// 解析一行 CSV 为 Record
std::optional<Record> parse_line(std::string_view line) {
// 用 views::split 按逗号拆分
auto fields = line
| std::views::split(',')
| std::views::transform([](auto&& rng) {
return trim(std::string_view(rng.begin(), rng.end()));
})
| std::ranges::to<std::vector<std::string>>();
// 需要恰好 5 个字段
if (fields.size() != 5) return std::nullopt;
// 解析数值字段
auto amount = parse_double(fields[3]);
auto quantity = parse_int(fields[4]);
// 任一数值字段无效则跳过该记录
if (!amount || !quantity) return std::nullopt;
return Record{
.name = std::move(fields[0]),
.region = std::move(fields[1]),
.category = std::move(fields[2]),
.amount = *amount,
.quantity = *quantity
};
}
为什么用 from_chars 而不是 stod?std::from_chars 不会抛异常、不受 locale 影响、性能更高。配合 optional 返回值,错误处理非常干净。
读取文件并批量解析:
// 从文件读取所有行
std::vector<std::string> read_lines(const std::string& filepath) {
std::vector<std::string> lines;
std::ifstream file(filepath);
std::string line;
while (std::getline(file, line)) {
lines.push_back(std::move(line));
}
return lines;
}
// 解析所有记录(跳过表头,过滤无效行)
std::vector<Record> parse_csv(const std::string& filepath) {
auto lines = read_lines(filepath);
return lines
| std::views::drop(1) // 跳过 CSV 表头
| std::views::transform(parse_line) // 尝试解析每行
| std::views::filter([](const auto& opt) {
return opt.has_value(); // 只保留成功的
})
| std::views::transform([](auto&& opt) {
return *std::move(opt); // 解包 optional
})
| std::ranges::to<std::vector>(); // 收集为 vector
}
注意:views::split 在 C++20 中返回的子范围不保证以 '\0' 结尾,不能直接用作 C 字符串。始终通过 string_view 或拷贝为 string 来使用。
4. 过滤与转换
拿到原始记录后,通过链式管道完成筛选和转换。以下示例展示了多种过滤条件的组合:
// 过滤条件:金额大于等于阈值
auto amount_at_least(double threshold) {
return [threshold](const Record& r) {
return r.amount >= threshold;
};
}
// 过滤条件:指定区域
auto in_region(std::string_view region) {
return [region = std::string(region)](const Record& r) {
return r.region == region;
};
}
// 过滤条件:指定品类
auto in_category(std::string_view category) {
return [category = std::string(category)](const Record& r) {
return r.category == category;
};
}
// 使用示例:筛选华东地区金额 >= 5000 的记录
void demo_filter(const std::vector<Record>& records) {
auto results = records
| std::views::filter(in_region("华东"))
| std::views::filter(amount_at_least(5000.0));
for (const auto& r : results) {
std::println(" {} - ¥{:.2f}", r.name, r.amount);
}
}
转换阶段:为每条记录计算派生信息,生成新的聚合结构:
// 带评级的增强记录
struct EnrichedRecord {
std::string name;
std::string region;
std::string category;
double amount;
int quantity;
double unit_price;
Rating rating;
};
// transform:将 Record 转为 EnrichedRecord
auto enrich(const Record& r) -> EnrichedRecord {
return {
.name = r.name,
.region = r.region,
.category = r.category,
.amount = r.amount,
.quantity = r.quantity,
.unit_price = r.unit_price(),
.rating = compute_rating(r.amount)
};
}
// 管道:过滤 + 转换 + 排序
std::vector<EnrichedRecord> process(const std::vector<Record>& records) {
auto enriched = records
| std::views::filter(amount_at_least(3000.0)) // 最低金额门槛
| std::views::transform(enrich) // 添加派生字段
| std::ranges::to<std::vector>();
// 按金额降序排序(使用投影)
std::ranges::sort(enriched, std::greater{}, &EnrichedRecord::amount);
return enriched;
}
投影(Projection)的优势:std::ranges::sort(vec, std::greater{}, &EnrichedRecord::amount) 不需要写完整的比较 lambda,代码意图更清晰。投影可以是成员指针、成员函数指针或任意一元函数。
5. 聚合与统计
聚合是数据管道的核心价值所在。我们用 std::map 实现分组统计:
// 统计摘要
struct Stats {
int count = 0;
double total = 0.0;
double min_val = std::numeric_limits<double>::max();
double max_val = std::numeric_limits<double>::lowest();
void add(double value) {
++count;
total += value;
min_val = std::min(min_val, value);
max_val = std::max(max_val, value);
}
double average() const {
return count > 0 ? total / count : 0.0;
}
};
// 按区域分组统计
auto group_by_region(const std::vector<Record>& records) {
std::map<std::string, Stats> groups;
for (const auto& r : records) {
groups[r.region].add(r.amount);
}
return groups;
}
// 按品类分组统计
auto group_by_category(const std::vector<Record>& records) {
std::map<std::string, Stats> groups;
for (const auto& r : records) {
groups[r.category].add(r.amount);
}
return groups;
}
// 全局统计(使用 ranges 算法)
void print_global_stats(const std::vector<Record>& records) {
if (records.empty()) {
std::println("无数据");
return;
}
// 总金额
double total = std::ranges::fold_left(
records | std::views::transform(&Record::amount),
0.0, std::plus{}
);
// 最大/最小金额记录
auto [min_it, max_it] = std::ranges::minmax_element(
records, {}, &Record::amount
);
// 平均数量
double avg_qty = static_cast<double>(
std::ranges::fold_left(
records | std::views::transform(&Record::quantity),
0, std::plus{}
)
) / records.size();
std::println("=== 全局统计 ===");
std::println(" 记录数: {}", records.size());
std::println(" 总金额: ¥{:.2f}", total);
std::println(" 平均数量: {:.1f}", avg_qty);
std::println(" 最高: {} (¥{:.2f})", max_it->name, max_it->amount);
std::println(" 最低: {} (¥{:.2f})", min_it->name, min_it->amount);
}
使用 ranges::fold_left(C++23)替代 std::accumulate,它支持管道中的视图而不要求容器迭代器。ranges::minmax_element 一次遍历同时找到最小和最大值。
6. 格式化输出
使用 std::format / std::println 生成对齐的表格输出:
// 打印分组统计表
void print_group_table(const std::string& title,
const std::map<std::string, Stats>& groups) {
std::println("\n=== {} ===", title);
std::println("{:<10} {:>6} {:>12} {:>12} {:>12} {:>12}",
"分组", "笔数", "总金额", "平均", "最低", "最高");
std::println("{:-<70}", "");
for (const auto& [key, stats] : groups) {
std::println("{:<10} {:>6} {:>12.2f} {:>12.2f} {:>12.2f} {:>12.2f}",
key, stats.count, stats.total,
stats.average(), stats.min_val, stats.max_val);
}
}
// 打印详细记录表(带评级)
void print_enriched_table(const std::vector<EnrichedRecord>& records) {
std::println("\n=== 销售明细(按金额降序) ===");
std::println("{:<8} {:<6} {:<10} {:>10} {:>6} {:>10} {:<6}",
"姓名", "区域", "品类", "金额", "数量", "单价", "评级");
std::println("{:-<62}", "");
for (const auto& r : records) {
std::println("{:<8} {:<6} {:<10} {:>10.2f} {:>6} {:>10.2f} {:<6}",
r.name, r.region, r.category,
r.amount, r.quantity, r.unit_price,
rating_label(r.rating));
}
}
对齐技巧:{:<10} 左对齐宽度 10,{:>12.2f} 右对齐宽度 12 保留 2 位小数。中文字符在等宽字体中通常占 2 个字符宽度,实际宽度需根据终端调整。
7. 完整程序
下面是将所有组件整合到一起的完整程序。你可以直接编译运行:
// sales_pipeline.cpp
// 编译: g++ -std=c++23 -O2 sales_pipeline.cpp -o sales_pipeline
#include <algorithm>
#include <charconv>
#include <fstream>
#include <iostream>
#include <limits>
#include <map>
#include <numeric>
#include <optional>
#include <print>
#include <ranges>
#include <string>
#include <string_view>
#include <vector>
// ─── 数据模型 ───────────────────────────────────────────────
struct Record {
std::string name;
std::string region;
std::string category;
double amount{};
int quantity{};
double unit_price() const {
return quantity > 0 ? amount / quantity : 0.0;
}
};
enum class Rating { Bronze, Silver, Gold, Platinum };
std::string_view rating_label(Rating r) {
switch (r) {
case Rating::Bronze: return "铜牌";
case Rating::Silver: return "银牌";
case Rating::Gold: return "金牌";
case Rating::Platinum: return "白金";
}
return "未知";
}
Rating compute_rating(double amount) {
if (amount >= 25000) return Rating::Platinum;
if (amount >= 15000) return Rating::Gold;
if (amount >= 8000) return Rating::Silver;
return Rating::Bronze;
}
struct EnrichedRecord {
std::string name;
std::string region;
std::string category;
double amount{};
int quantity{};
double unit_price{};
Rating rating{};
};
struct Stats {
int count = 0;
double total = 0.0;
double min_val = std::numeric_limits<double>::max();
double max_val = std::numeric_limits<double>::lowest();
void add(double value) {
++count;
total += value;
min_val = std::min(min_val, value);
max_val = std::max(max_val, value);
}
double average() const { return count > 0 ? total / count : 0.0; }
};
// ─── 解析层 ─────────────────────────────────────────────────
std::string trim(std::string_view sv) {
auto start = sv.find_first_not_of(" \t\r\n");
if (start == std::string_view::npos) return "";
auto end = sv.find_last_not_of(" \t\r\n");
return std::string(sv.substr(start, end - start + 1));
}
std::optional<double> parse_double(std::string_view sv) {
double val{};
auto [ptr, ec] = std::from_chars(sv.data(), sv.data() + sv.size(), val);
return ec == std::errc{} ? std::optional{val} : std::nullopt;
}
std::optional<int> parse_int(std::string_view sv) {
int val{};
auto [ptr, ec] = std::from_chars(sv.data(), sv.data() + sv.size(), val);
return ec == std::errc{} ? std::optional{val} : std::nullopt;
}
std::optional<Record> parse_line(std::string_view line) {
auto fields = line
| std::views::split(',')
| std::views::transform([](auto&& rng) {
return trim(std::string_view(rng.begin(), rng.end()));
})
| std::ranges::to<std::vector<std::string>>();
if (fields.size() != 5) return std::nullopt;
auto amount = parse_double(fields[3]);
auto quantity = parse_int(fields[4]);
if (!amount || !quantity) return std::nullopt;
return Record{
.name = std::move(fields[0]),
.region = std::move(fields[1]),
.category = std::move(fields[2]),
.amount = *amount,
.quantity = *quantity
};
}
std::vector<std::string> read_lines(const std::string& path) {
std::vector<std::string> lines;
std::ifstream file(path);
for (std::string line; std::getline(file, line); ) {
lines.push_back(std::move(line));
}
return lines;
}
// ─── 管道核心 ───────────────────────────────────────────────
std::vector<Record> load_records(const std::string& path) {
auto lines = read_lines(path);
return lines
| std::views::drop(1) // 跳过表头
| std::views::transform([](const std::string& s) {
return parse_line(s); // 解析
})
| std::views::filter(&std::optional<Record>::has_value) // 过滤失败
| std::views::transform([](auto&& opt) {
return *std::move(opt); // 解包
})
| std::ranges::to<std::vector>();
}
std::vector<EnrichedRecord> build_pipeline(const std::vector<Record>& records) {
auto enriched = records
| std::views::filter([](const Record& r) {
return r.amount > 0 && r.quantity > 0; // 有效记录
})
| std::views::transform([](const Record& r) -> EnrichedRecord {
return { r.name, r.region, r.category,
r.amount, r.quantity,
r.unit_price(), compute_rating(r.amount) };
})
| std::ranges::to<std::vector>();
// 按金额降序排序
std::ranges::sort(enriched, std::greater{}, &EnrichedRecord::amount);
return enriched;
}
// ─── 聚合 ───────────────────────────────────────────────────
auto aggregate_by(const std::vector<Record>& records,
auto projection) {
std::map<std::string, Stats> groups;
for (const auto& r : records) {
groups[std::invoke(projection, r)].add(r.amount);
}
return groups;
}
// ─── 输出 ───────────────────────────────────────────────────
void print_detail(const std::vector<EnrichedRecord>& data) {
std::println("\n┌─ 销售明细(按金额降序)─────────────────────────┐");
std::println("{:<8}{:<6}{:<10}{:>10}{:>6}{:>10} {:<4}",
"姓名", "区域", "品类", "金额", "数量", "单价", "评级");
std::println("{:-<60}", "");
for (const auto& r : data) {
std::println("{:<8}{:<6}{:<10}{:>10.2f}{:>6}{:>10.2f} {:<4}",
r.name, r.region, r.category,
r.amount, r.quantity, r.unit_price,
rating_label(r.rating));
}
}
void print_stats(const std::string& title,
const std::map<std::string, Stats>& groups) {
std::println("\n┌─ {} ────────────────────────────────────────┐", title);
std::println("{:<10}{:>6}{:>12}{:>12}{:>12}{:>12}",
"分组", "笔数", "总金额", "平均", "最低", "最高");
std::println("{:-<66}", "");
for (const auto& [key, s] : groups) {
std::println("{:<10}{:>6}{:>12.2f}{:>12.2f}{:>12.2f}{:>12.2f}",
key, s.count, s.total,
s.average(), s.min_val, s.max_val);
}
}
void print_summary(const std::vector<Record>& records) {
auto total = std::ranges::fold_left(
records | std::views::transform(&Record::amount),
0.0, std::plus{});
auto [lo, hi] = std::ranges::minmax_element(records, {}, &Record::amount);
std::println("\n┌─ 全局摘要 ─────────────────────────────────────┐");
std::println(" 总记录数: {}", records.size());
std::println(" 总金额: ¥{:.2f}", total);
std::println(" 最高单笔: {} ¥{:.2f}", hi->name, hi->amount);
std::println(" 最低单笔: {} ¥{:.2f}", lo->name, lo->amount);
}
// ─── 主函数 ─────────────────────────────────────────────────
int main(int argc, char* argv[]) {
std::string filepath = (argc > 1) ? argv[1] : "sales.csv";
// 阶段 1: 加载并解析
auto records = load_records(filepath);
if (records.empty()) {
std::println(stderr, "错误: 无法读取或解析 '{}'", filepath);
return 1;
}
std::println("已加载 {} 条有效记录。", records.size());
// 阶段 2: 构建增强管道
auto enriched = build_pipeline(records);
// 阶段 3: 输出
print_detail(enriched);
print_stats("按区域统计", aggregate_by(records, &Record::region));
print_stats("按品类统计", aggregate_by(records, &Record::category));
print_summary(records);
return 0;
}
编译器要求:本程序需要 C++23 支持。GCC 13+、Clang 17+、MSVC 17.7+ 均可编译。如果编译器不支持 std::println,可替换为 std::cout << std::format(...) << '\n'。如果不支持 ranges::fold_left,可用 std::accumulate 配合 ranges::to<vector> 替代。
示例输出:
已加载 10 条有效记录。
┌─ 销售明细(按金额降序)─────────────────────────┐
姓名 区域 品类 金额 数量 单价 评级
------------------------------------------------------------
孙悦 华南 电子产品 31000.00 2 15500.00 白金
王强 华南 电子产品 23000.00 5 4600.00 金牌
陈刚 华北 电子产品 18700.00 4 4675.00 金牌
张伟 华东 电子产品 12500.00 3 4166.67 银牌
马超 华东 家居用品 11500.00 6 1916.67 银牌
李娜 华北 家居用品 8900.50 7 1271.50 银牌
刘洋 华南 家居用品 6200.00 9 688.89 铜牌
吴磊 华北 食品饮料 5100.00 8 637.50 铜牌
赵敏 华东 食品饮料 4500.00 12 375.00 铜牌
周芳 华东 食品饮料 3200.00 15 213.33 铜牌
┌─ 按区域统计 ────────────────────────────────────────┐
分组 笔数 总金额 平均 最低 最高
------------------------------------------------------------------
华东 4 31700.00 7925.00 3200.00 12500.00
华北 3 32700.50 10900.17 5100.00 18700.00
华南 3 60200.00 20066.67 6200.00 31000.00
┌─ 按品类统计 ────────────────────────────────────────┐
分组 笔数 总金额 平均 最低 最高
------------------------------------------------------------------
电子产品 4 85200.00 21300.00 12500.00 31000.00
家居用品 3 26600.50 8866.83 6200.00 11500.00
食品饮料 3 12800.00 4266.67 3200.00 5100.00
┌─ 全局摘要 ─────────────────────────────────────────┐
总记录数: 10
总金额: ¥124600.50
最高单笔: 孙悦 ¥31000.00
最低单笔: 周芳 ¥3200.00
8. 扩展练习
以下练习帮助你进一步巩固管道思维:
练习 1:添加排序选项
支持按不同字段排序。提示:用 std::function 或模板封装投影:
// 根据命令行参数选择排序字段
auto get_projection(std::string_view field) {
using Proj = double(*)(const EnrichedRecord&);
static std::map<std::string_view, Proj> projections = {
{"amount", [](const EnrichedRecord& r) { return r.amount; }},
{"unit_price", [](const EnrichedRecord& r) { return r.unit_price; }},
{"quantity", [](const EnrichedRecord& r) {
return static_cast<double>(r.quantity); }}
};
auto it = projections.find(field);
return it != projections.end() ? it->second : projections["amount"];
}
// 用法:
auto proj = get_projection(sort_field);
std::ranges::sort(enriched, std::greater{}, proj);
练习 2:输出到文件
将结果写入 CSV 文件,使用 std::ofstream + std::format:
void export_csv(const std::vector<EnrichedRecord>& data,
const std::string& output_path) {
std::ofstream out(output_path);
out << "name,region,category,amount,quantity,unit_price,rating\n";
for (const auto& r : data) {
out << std::format("{},{},{},{:.2f},{},{:.2f},{}\n",
r.name, r.region, r.category,
r.amount, r.quantity, r.unit_price,
rating_label(r.rating));
}
std::println("已导出 {} 条记录到 {}", data.size(), output_path);
}
练习 3:命令行参数解析
用简单的参数解析让工具更通用:
struct Options {
std::string input_file = "sales.csv";
std::string output_file; // 空表示不导出
std::string sort_by = "amount";
std::optional<std::string> filter_region;
double min_amount = 0.0;
};
Options parse_args(int argc, char* argv[]) {
Options opts;
for (int i = 1; i < argc; ++i) {
std::string_view arg = argv[i];
if (arg == "--input" && i + 1 < argc) {
opts.input_file = argv[++i];
} else if (arg == "--output" && i + 1 < argc) {
opts.output_file = argv[++i];
} else if (arg == "--sort" && i + 1 < argc) {
opts.sort_by = argv[++i];
} else if (arg == "--region" && i + 1 < argc) {
opts.filter_region = argv[++i];
} else if (arg == "--min-amount" && i + 1 < argc) {
opts.min_amount = parse_double(argv[++i]).value_or(0.0);
}
}
return opts;
}
// 用法: ./sales_pipeline --input data.csv --region 华东 --min-amount 5000 --sort unit_price
练习 4:Top-N 查询
使用 ranges::partial_sort 或 views::take 实现 Top-N:
void print_top_n(const std::vector<EnrichedRecord>& data, int n) {
std::println("\n=== Top {} 销售 ===", n);
for (const auto& r : data | std::views::take(n)) {
std::println(" {} - {} - ¥{:.2f} ({})",
r.name, r.category, r.amount,
rating_label(r.rating));
}
}
本章小结
- 管道思维:数据从原始文本经过解析→过滤→转换→聚合→输出,每一步都是独立、可组合的
- views::split + from_chars:零分配的 CSV 解析,配合
optional优雅表达"可能失败" - views::filter + transform:声明式地表达业务逻辑,而非手动循环
- 投影排序:
ranges::sort(vec, comp, projection)比写完整比较函数更清晰 - ranges::fold_left + minmax_element:聚合统计只需一行
- std::format / println:类型安全、可读性强的格式化输出
- 工厂函数返回 Lambda:
amount_at_least(5000)这种模式让过滤条件可复用、可参数化
本章综合运用了卷二所有核心知识点。掌握这种管道式数据处理风格后,你会发现许多实际业务逻辑都可以用同样的模式表达——读取、验证、转换、聚合、输出。