控制流与结构化绑定

控制流是程序的骨架。现代 C++ 没有发明全新的控制结构,而是在经典语法上做了精准增强:if 初始化语句缩小变量作用域、结构化绑定消除冗余的 .first/.second、range-for 让循环更简洁安全。本章将逐一展开这些特性,帮助你写出既清晰又现代的流程控制代码。

if / else 与初始化语句

基础 if/else

C++ 的 if/else 语法与 C 相同,但现代风格建议:

  • 条件表达式中避免隐式转换(使用显式比较而非裸指针判断)
  • 单行语句也加花括号,防止后续修改引入 bug
int score = 85;

if (score >= 90) {
    std::println("优秀");
} else if (score >= 60) {
    std::println("及格");
} else {
    std::println("不及格");
}

if with initializer(C++17)

C++17 允许在 if 语句中声明变量,语法为 if (init; condition)。这将变量的作用域严格限制在 if/else 块内,不会泄漏到外部:

#include <map>
#include <string>
#include <print>

std::map<std::string, int> config{{"timeout", 30}, {"retries", 3}};

// C++17: if with initializer
if (auto it = config.find("timeout"); it != config.end()) {
    std::println("timeout = {}", it->second);
} else {
    std::println("timeout 未配置,使用默认值");
}
// it 在此处不可见,不会污染外部作用域

为什么用 if-init? 在 C++17 之前,it 必须在 if 之前声明,导致它的生命期长于实际需要。if-init 让"声明 + 判断"合为一体,代码更紧凑,作用域更干净。

另一个常见场景 —— 在字符串中查找子串:

std::string text = "Learning Modern C++ is fun";

if (auto pos = text.find("C++"); pos != std::string::npos) {
    std::println("Found 'C++' at position {}", pos);
} else {
    std::println("'C++' not found");
}

与 set.insert() 配合使用(结合结构化绑定):

std::set<int> numbers{1, 2, 3, 4, 5};

if (auto [iter, inserted] = numbers.insert(3); !inserted) {
    std::println("值 {} 已存在", *iter);
}

constexpr if(简要提及)

if constexpr 是编译期条件分支,主要用于模板编程中根据类型特征选择不同代码路径。我们将在卷四(泛型编程)深入讲解,这里先看一个直观的例子:

template <typename T>
auto to_string(T value) {
    if constexpr (std::is_arithmetic_v<T>) {
        return std::to_string(value);  // 数值类型
    } else {
        return std::string(value);     // 假设可以转换为 string
    }
}

注意:if constexpr 只能在模板上下文中根据模板参数做分支。在普通函数中,用 if constexpr 和普通 if 没有区别(如果条件是编译期常量,编译器本来就会优化掉死分支)。

switch 语句

现代 switch 与 [[fallthrough]]

传统 C/C++ 的 switch 中,忘记写 break 会导致"贯穿"(fallthrough)到下一个 case。这是常见的 bug 来源。C++17 引入了 [[fallthrough]] 属性,明确标注有意为之的贯穿,让编译器在无标注时发出警告:

enum class Status { ok, warning, error, critical };

void handle(Status status) {
    switch (status) {
        case Status::ok:
            std::println("一切正常");
            break;

        case Status::warning:
            log_warning();
            [[fallthrough]];  // 明确标注:有意贯穿到 error 的处理

        case Status::error:
            notify_admin();
            break;

        case Status::critical:
            shutdown_system();
            break;
    }
}

编译器警告:开启 -Wimplicit-fallthrough(GCC/Clang)后,没有 [[fallthrough]] 标注的贯穿会产生警告。这能帮助你在代码审查前就发现遗漏的 break。

switch with initializer(C++17)

与 if 类似,switch 也支持初始化语句:

switch (auto ch = read_char(); ch) {
    case 'q': quit(); break;
    case 's': save(); break;
    default:  process(ch); break;
}

using enum(C++20)

使用 scoped enum 时,每个 case 都要写 EnumName::value,略显冗长。C++20 的 using enum 可以在局部引入枚举值:

enum class Color { red, green, blue };

std::string_view color_name(Color c) {
    using enum Color;  // C++20: 引入所有枚举值到当前作用域
    switch (c) {
        case red:   return "红色";
        case green: return "绿色";
        case blue:  return "蓝色";
    }
    std::unreachable();  // C++23: 标注此处不可达
}

using enum 的作用域仅限于它所在的块。在 switch 的函数体中使用不会污染外部命名空间。

Range-based for 循环

基础语法

Range-based for(范围 for 循环)是 C++11 引入的,用于遍历任何提供 begin()/end() 的容器或范围:

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

// 只读遍历
for (const auto& n : numbers) {
    std::println("{}", n);
}

// 需要修改元素
for (auto& n : numbers) {
    n *= 2;  // 每个元素翻倍
}

auto 的引用形式选择

Range-for 中 auto 的写法直接影响性能和语义:

写法 含义 适用场景
const auto& 只读引用,无拷贝 只需读取(最常用)
auto& 可变引用,无拷贝 需要修改元素
auto 按值拷贝 小类型(int, char)或需要局部副本
auto&& 转发引用 泛型代码或代理迭代器(如 vector<bool>)

性能陷阱:对于 std::string、std::vector 等大类型,如果只需要读取,务必用 const auto& 而非 auto。后者会在每次迭代中执行拷贝!

Range-for 配合结构化绑定遍历 map

这是现代 C++ 中最优雅的写法之一:

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

// C++17: 结构化绑定 + range-for
for (const auto& [name, score] : scores) {
    std::println("{}: {}", name, score);
}
// 输出:
// Alice: 95
// Bob: 87
// Charlie: 92

索引循环 vs Range-for

绝大多数情况下,优先使用 range-for:

std::vector<std::string> names{"Alice", "Bob", "Charlie"};

// [错误] 传统索引循环 —— 冗长且容易出错(off-by-one)
for (std::size_t i = 0; i < names.size(); ++i) {
    std::println("{}", names[i]);
}

// [正确] Range-for —— 简洁安全
for (const auto& name : names) {
    std::println("{}", name);
}

什么时候还需要索引?当你确实需要位置信息时:

// 需要索引的场景:打印带编号的列表
for (std::size_t i = 0; i < names.size(); ++i) {
    std::println("{}. {}", i + 1, names[i]);
}

// C++23 替代方案:std::views::enumerate
for (auto [idx, name] : std::views::enumerate(names)) {
    std::println("{}. {}", idx + 1, name);
}

结构化绑定(Structured Bindings, C++17)

结构化绑定是 C++17 最受欢迎的特性之一。它允许你用一条声明语句将聚合类型"解包"为独立的命名变量,消除了以前用 .first、.second、std::get<0>() 等访问方式带来的可读性问题。

分解 std::pair

#include <algorithm>
#include <print>

// std::minmax 返回 std::pair
auto [min_val, max_val] = std::minmax({3, 1, 4, 1, 5, 9, 2, 6});
std::println("min = {}, max = {}", min_val, max_val);
// 输出: min = 1, max = 9

// 对比旧写法:
auto result = std::minmax({3, 1, 4, 1, 5, 9, 2, 6});
std::println("min = {}, max = {}", result.first, result.second);  // .first/.second 可读性差

分解自定义结构体

结构化绑定可以直接用于所有公开成员的结构体(aggregate 类型):

struct Point {
    double x;
    double y;
    double z;
};

Point get_position() {
    return {1.0, 2.5, -3.0};
}

// 分解结构体
auto [x, y, z] = get_position();
std::println("位置: ({}, {}, {})", x, y, z);

// 也可以使用引用,避免拷贝
Point origin{0.0, 0.0, 0.0};
auto& [ox, oy, oz] = origin;
oz = 1.0;  // 修改了 origin.z

与 map 配合:最经典的用法

std::map<std::string, std::vector<int>> student_scores{
    {"Alice",   {90, 85, 92}},
    {"Bob",     {78, 82, 80}},
    {"Charlie", {95, 98, 97}},
};

for (const auto& [name, scores] : student_scores) {
    auto avg = std::reduce(scores.begin(), scores.end(), 0.0) / scores.size();
    std::println("{} 的平均分: {:.1f}", name, avg);
}

分解数组

#include <array>

std::array<int, 3> rgb{255, 128, 0};
auto [r, g, b] = rgb;
std::println("R={}, G={}, B={}", r, g, b);

// 也适用于 C 风格数组
int coords[] = {10, 20};
auto [cx, cy] = coords;
std::println("({}, {})", cx, cy);

分解 std::tuple

#include <tuple>

std::tuple<std::string, int, bool> get_user_info() {
    return {"Alice", 25, true};
}

auto [name, age, active] = get_user_info();
std::println("用户: {}, 年龄: {}, 活跃: {}", name, age, active);

绑定数量必须完全匹配。如果结构体有 3 个成员,你的绑定声明也必须写 3 个名字 —— 不能多也不能少。不需要的值也必须命名(通常用 _ 前缀表示不关心)。

实战组合:insert + 结构化绑定 + if-init

当这些特性组合在一起时,代码的表达力会大幅提升:

std::map<std::string, int> inventory{{"apple", 10}, {"banana", 5}};

// 尝试插入,如果已存在则更新
if (auto [it, inserted] = inventory.try_emplace("apple", 20); !inserted) {
    std::println("'{}' 已存在,当前数量: {}", it->first, it->second);
    it->second += 20;  // 追加数量
    std::println("更新后: {}", it->second);
}

while 和 do-while

基础 while 循环

while 适用于循环次数不确定的场景:

// 从输入读取直到遇到终止条件
std::string line;
while (std::getline(std::cin, line)) {
    if (line == "quit") break;
    process(line);
}

// 数值迭代
int n = 1;
while (n <= 1024) {
    std::println("{}", n);
    n *= 2;
}

do-while:至少执行一次

do-while 在实际现代 C++ 代码中相对少见,但在"先执行再判断"的场景中仍有用武之地:

// 菜单交互:至少显示一次
int choice;
do {
    std::println("1. 新建  2. 打开  3. 退出");
    std::print("请选择: ");
    std::cin >> choice;
} while (choice < 1 || choice > 3);

规则:如果你在遍历一个集合,用 range-for;如果循环次数已知,用 range-for 或传统 for;只有在"不确定何时终止"时,才用 while。

现代循环哲学

"优先算法,慎用裸循环"

C++ Core Guidelines 的建议是:优先使用标准算法而非手写循环。算法名称本身就是文档,经过高度优化,且不容易出错:

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

// [错误] 手写循环找最大值
int max_val = data[0];
for (std::size_t i = 1; i < data.size(); ++i) {
    if (data[i] > max_val) max_val = data[i];
}

// [正确] 使用算法 —— 意图一目了然
auto max_val2 = std::ranges::max(data);

// [错误] 手写循环做变换
std::vector<int> doubled;
for (const auto& x : data) {
    doubled.push_back(x * 2);
}

// [正确] 使用 ranges(卷二详解)
auto doubled2 = data | std::views::transform([](int x) { return x * 2; })
                     | std::ranges::to<std::vector>();

何时裸循环仍然合适

不要教条。以下场景中手写循环可能更清晰:

  • 复杂的状态机 —— 循环体内有多个阶段和状态转换
  • 提前退出(break/continue)逻辑复杂 —— 算法难以表达"在中间某处跳出"
  • 需要同时操作多个容器 —— 无法用单一 range 表示
  • 性能关键路径 —— 需要手动控制内存访问模式
// 合适用裸循环的场景:解析状态机
enum class State { start, in_word, in_number };
State state = State::start;

for (char ch : input) {
    switch (state) {
        case State::start:
            if (std::isalpha(ch)) state = State::in_word;
            else if (std::isdigit(ch)) state = State::in_number;
            break;
        case State::in_word:
            if (!std::isalpha(ch)) { emit_word(); state = State::start; }
            break;
        case State::in_number:
            if (!std::isdigit(ch)) { emit_number(); state = State::start; }
            break;
    }
}

判断依据:如果一个循环能用一个标准算法名称概括(sort、find、transform、accumulate...),就用算法。如果循环体本身就是核心逻辑(状态机、协议解析),那手写循环更直接。

本章小结

  • if-init(C++17):在 if 中声明变量,限制作用域,避免泄漏
  • [[fallthrough]](C++17):标注有意的 switch 贯穿,配合编译器警告消灭 bug
  • using enum(C++20):在 switch 中省略枚举类型前缀,让代码更简洁
  • Range-for:遍历容器的首选方式,注意区分 const auto&、auto&、auto
  • 结构化绑定(C++17):解包 pair/tuple/struct/array,配合 range-for 遍历 map 特别优雅
  • 现代循环哲学:优先算法,裸循环留给复杂状态逻辑