Python 中的循环结构详解

文章目录

Python 中的循环结构详解

Python 提供了两种主要的循环结构:while 循环for 循环。以下是详细介绍和代码示例。

1. while 循环 - 基于条件的循环

基本语法

python 复制代码
while 条件:
    # 循环体
    # 当条件为 True 时重复执行

示例1:基本 while 循环

python 复制代码
# 计数器循环
count = 0
while count < 5:
    print(f"当前计数: {count}")
    count += 1  # 重要:必须更新条件变量,否则会无限循环

print("循环结束")
# 输出:
# 当前计数: 0
# 当前计数: 1
# 当前计数: 2
# 当前计数: 3
# 当前计数: 4
# 循环结束

示例2:用户输入验证

python 复制代码
# 循环直到用户输入有效的数字
while True:
    user_input = input("请输入一个数字(输入 'quit' 退出): ")
    
    if user_input.lower() == 'quit':
        print("退出程序")
        break
    
    if user_input.isdigit():
        num = int(user_input)
        print(f"你输入的数字是: {num}")
        print(f"它的平方是: {num ** 2}")
    else:
        print("无效输入,请重新输入")

示例3:循环控制语句

python 复制代码
# 使用 break, continue, else
count = 0
while count < 10:
    count += 1
    
    if count == 3:
        print("跳过 3")
        continue  # 跳过本次循环的剩余部分
    
    if count == 7:
        print("在 7 处中断循环")
        break  # 完全退出循环
    
    print(f"当前值: {count}")
else:
    # 如果循环正常结束(没有遇到break),执行else块
    print("循环正常结束")

print("程序继续执行")
# 输出:
# 当前值: 1
# 当前值: 2
# 跳过 3
# 当前值: 4
# 当前值: 5
# 当前值: 6
# 在 7 处中断循环
# 程序继续执行

示例4:密码验证系统

python 复制代码
# 密码验证,最多尝试3次
max_attempts = 3
attempts = 0
correct_password = "python123"

while attempts < max_attempts:
    password = input("请输入密码: ")
    attempts += 1
    
    if password == correct_password:
        print("登录成功!")
        break
    else:
        remaining = max_attempts - attempts
        if remaining > 0:
            print(f"密码错误,还剩 {remaining} 次尝试机会")
        else:
            print("密码错误,账户已锁定")
else:
    # 如果循环正常结束(没有遇到break),说明所有尝试都失败了
    print("已超过最大尝试次数")

2. for 循环 - 遍历序列的循环

基本语法

python 复制代码
for 变量 in 可迭代对象:
    # 循环体
    # 对可迭代对象中的每个元素执行

示例1:遍历列表

python 复制代码
# 遍历列表
fruits = ["苹果", "香蕉", "橙子", "葡萄"]

print("水果列表:")
for fruit in fruits:
    print(f"- {fruit}")

# 带索引的遍历
print("\n带索引的水果列表:")
for index, fruit in enumerate(fruits):
    print(f"{index + 1}. {fruit}")
    
# 输出:
# 水果列表:
# - 苹果
# - 香蕉
# - 橙子
# - 葡萄
# 
# 带索引的水果列表:
# 1. 苹果
# 2. 香蕉
# 3. 橙子
# 4. 葡萄

示例2:遍历字符串

python 复制代码
# 遍历字符串
word = "Python"

print("字符串中的字符:")
for char in word:
    print(char)

# 输出:
# 字符串中的字符:
# P
# y
# t
# h
# o
# n

示例3:使用 range() 函数

python 复制代码
# range() 生成数字序列
print("0到4:")
for i in range(5):  # 0, 1, 2, 3, 4
    print(i)

print("\n2到6:")
for i in range(2, 7):  # 2, 3, 4, 5, 6
    print(i)

print("\n0到10,步长为2:")
for i in range(0, 11, 2):  # 0, 2, 4, 6, 8, 10
    print(i)

print("\n10到0,递减:")
for i in range(10, -1, -1):  # 10, 9, 8, ..., 0
    print(i)

示例4:遍历字典

python 复制代码
# 遍历字典
student = {
    "name": "张三",
    "age": 20,
    "major": "计算机科学",
    "gpa": 3.8
}

print("学生信息:")
# 遍历键
print("键:")
for key in student:
    print(key)

print("\n键值对:")
# 遍历键值对
for key, value in student.items():
    print(f"{key}: {value}")

print("\n值:")
# 遍历值
for value in student.values():
    print(value)

# 输出:
# 学生信息:
# 键:
# name
# age
# major
# gpa
# 
# 键值对:
# name: 张三
# age: 20
# major: 计算机科学
# gpa: 3.8
# 
# 值:
# 张三
# 20
# 计算机科学
# 3.8

示例5:嵌套循环

python 复制代码
# 嵌套循环 - 打印乘法表
print("乘法表:")
for i in range(1, 10):  # 外层循环
    for j in range(1, i + 1):  # 内层循环
        print(f"{j} × {i} = {i * j:2d}", end="  ")
    print()  # 换行

# 输出:
# 乘法表:
# 1 × 1 =  1  
# 1 × 2 =  2  2 × 2 =  4  
# 1 × 3 =  3  2 × 3 =  6  3 × 3 =  9  
# ... 以此类推

3. while vs for 循环对比

特性 while 循环 for 循环
使用场景 不确定循环次数时 已知循环次数或遍历序列时
语法 while 条件: for 变量 in 可迭代对象:
条件控制 需要在循环体内更新条件 自动遍历,无需手动更新
无限循环 容易造成(如果条件永远为True) 通常不会(除非可迭代对象无限)
典型应用 用户输入验证、游戏主循环 遍历列表/字符串、固定次数循环

4. 循环控制语句

break - 立即退出循环

python 复制代码
# break 示例
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

print("查找第一个能被7整除的数:")
for num in numbers:
    if num % 7 == 0:
        print(f"找到: {num}")
        break
else:
    print("没有找到能被7整除的数")

continue - 跳过本次循环剩余部分

python 复制代码
# continue 示例
print("打印1-10中的奇数:")
for i in range(1, 11):
    if i % 2 == 0:
        continue  # 跳过偶数
    print(i)

else - 循环正常结束后执行

python 复制代码
# else 示例 - 在for循环中
numbers = [2, 4, 6, 8, 10]

print("检查列表中是否有奇数:")
for num in numbers:
    if num % 2 != 0:
        print(f"找到奇数: {num}")
        break
else:
    print("列表中没有奇数")
    
# else 示例 - 在while循环中
count = 0
while count < 3:
    print(f"第 {count + 1} 次尝试")
    count += 1
else:
    print("所有尝试完成")

5. 高级循环技巧

列表推导式(List Comprehension)

python 复制代码
# 传统方式
squares = []
for x in range(10):
    squares.append(x ** 2)

# 列表推导式(更简洁)
squares = [x ** 2 for x in range(10)]
print(squares)  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# 带条件的列表推导式
even_squares = [x ** 2 for x in range(10) if x % 2 == 0]
print(even_squares)  # [0, 4, 16, 36, 64]

字典推导式

python 复制代码
# 创建数字到其平方的字典
squares_dict = {x: x ** 2 for x in range(5)}
print(squares_dict)  # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

# 使用两个列表创建字典
keys = ['name', 'age', 'city']
values = ['Alice', 25, 'New York']
person = {k: v for k, v in zip(keys, values)}
print(person)  # {'name': 'Alice', 'age': 25, 'city': 'New York'}

生成器表达式

python 复制代码
# 生成器表达式(节省内存)
numbers = (x ** 2 for x in range(1000000))  # 不立即创建所有元素
for num in numbers:
    if num > 100:
        break
    print(num, end=" ")

zip() 函数 - 同时遍历多个序列

python 复制代码
# 同时遍历多个列表
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
cities = ["New York", "London", "Paris"]

print("人员信息:")
for name, age, city in zip(names, ages, cities):
    print(f"{name} ({age}岁) 来自 {city}")

# 输出:
# 人员信息:
# Alice (25岁) 来自 New York
# Bob (30岁) 来自 London
# Charlie (35岁) 来自 Paris

6. 实用示例

示例1:猜数字游戏

python 复制代码
import random

def guess_number_game():
    """猜数字游戏"""
    number = random.randint(1, 100)
    attempts = 0
    max_attempts = 7
    
    print("欢迎来到猜数字游戏!")
    print(f"我想了一个1-100之间的数字,你有{max_attempts}次机会猜。")
    
    while attempts < max_attempts:
        attempts += 1
        remaining = max_attempts - attempts + 1
        
        try:
            guess = int(input(f"\n第{attempts}次尝试 (还剩{remaining}次): "))
        except ValueError:
            print("请输入有效的数字!")
            attempts -= 1  # 不计入有效尝试
            continue
        
        if guess < number:
            print(f"{guess} 太小了")
        elif guess > number:
            print(f"{guess} 太大了")
        else:
            print(f"恭喜!你在第{attempts}次猜中了数字 {number}")
            break
    else:
        print(f"\n游戏结束!数字是 {number}")

# 运行游戏
guess_number_game()

示例2:统计文本

python 复制代码
def analyze_text(text):
    """分析文本统计信息"""
    # 初始化计数器
    char_count = 0
    word_count = 0
    sentence_count = 0
    vowel_count = 0
    consonants_count = 0
    
    vowels = "aeiouAEIOU"
    
    # 遍历文本
    for char in text:
        char_count += 1
        
        # 统计元音和辅音
        if char.isalpha():
            if char in vowels:
                vowel_count += 1
            else:
                consonants_count += 1
    
    # 统计单词和句子
    words = text.split()
    word_count = len(words)
    
    # 简单句子分割(按句号、问号、感叹号)
    sentence_count = text.count('.') + text.count('?') + text.count('!')
    
    # 输出结果
    print("文本分析结果:")
    print(f"字符总数: {char_count}")
    print(f"单词总数: {word_count}")
    print(f"句子总数: {sentence_count}")
    print(f"元音字母数: {vowel_count}")
    print(f"辅音字母数: {consonants_count}")
    
    # 计算平均单词长度
    if word_count > 0:
        avg_word_length = sum(len(word) for word in words) / word_count
        print(f"平均单词长度: {avg_word_length:.2f}")

# 测试
text = "Python is a powerful programming language. It's easy to learn and use!"
analyze_text(text)

示例3:斐波那契数列生成器

python 复制代码
def fibonacci_sequence(n):
    """生成斐波那契数列的前n项"""
    if n <= 0:
        return []
    elif n == 1:
        return [0]
    elif n == 2:
        return [0, 1]
    
    # 初始化
    sequence = [0, 1]
    
    # 使用while循环
    while len(sequence) < n:
        next_num = sequence[-1] + sequence[-2]
        sequence.append(next_num)
    
    return sequence

def fibonacci_generator(n):
    """使用生成器生成斐波那契数列"""
    a, b = 0, 1
    count = 0
    
    while count < n:
        yield a
        a, b = b, a + b
        count += 1

# 测试
print("斐波那契数列前10项:")
print(fibonacci_sequence(10))

print("\n使用生成器:")
for num in fibonacci_generator(10):
    print(num, end=" ")

总结

Python 的循环结构非常强大且灵活:

  • while 循环适合不确定循环次数的场景
  • for 循环适合遍历序列或已知循环次数的场景
  • 循环控制语句(break、continue、else)提供了精细的流程控制
  • 推导式提供了更简洁的创建集合的方式
  • 生成器可以高效处理大量数据

掌握这些循环技巧对于编写高效、简洁的 Python 代码非常重要。



现代C++中的循环结构详解

现代C++提供了丰富的循环结构,包括传统的循环和现代的范围for循环。以下是详细介绍和代码示例。

1. while 循环 - 基于条件的循环

基本语法

cpp 复制代码
while (条件表达式) {
    // 循环体
}

示例1:基本 while 循环

cpp 复制代码
#include <iostream>

int main() {
    // 计数器循环
    int count = 0;
    while (count < 5) {
        std::cout << "当前计数: " << count << std::endl;
        ++count;  // 前缀递增通常更高效
    }

    std::cout << "循环结束" << std::endl;
    // 输出:
    // 当前计数: 0
    // 当前计数: 1
    // 当前计数: 2
    // 当前计数: 3
    // 当前计数: 4
    // 循环结束
}

示例2:用户输入验证

cpp 复制代码
#include <iostream>
#include <string>
#include <limits>

int main() {
    int number;
    
    // 循环直到用户输入有效的数字
    while (true) {
        std::cout << "请输入一个数字(输入-1退出): ";
        
        // 检查输入是否成功
        if (!(std::cin >> number)) {
            std::cout << "无效输入,请重新输入" << std::endl;
            std::cin.clear();  // 清除错误状态
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // 忽略错误输入
            continue;
        }
        
        if (number == -1) {
            std::cout << "退出程序" << std::endl;
            break;
        }
        
        std::cout << "你输入的数字是: " << number << std::endl;
        std::cout << "它的平方是: " << number * number << std::endl;
    }
    
    return 0;
}

示例3:do-while 循环(先执行后判断)

cpp 复制代码
#include <iostream>

int main() {
    int number;
    
    // do-while 至少执行一次
    do {
        std::cout << "请输入一个正数: ";
        std::cin >> number;
        
        if (number <= 0) {
            std::cout << "输入无效,请重新输入" << std::endl;
        }
    } while (number <= 0);
    
    std::cout << "你输入的正数是: " << number << std::endl;
    
    return 0;
}

示例4:循环控制语句

cpp 复制代码
#include <iostream>

int main() {
    // 使用 break, continue
    int count = 0;
    while (count < 10) {
        ++count;
        
        if (count == 3) {
            std::cout << "跳过 3" << std::endl;
            continue;  // 跳过本次循环的剩余部分
        }
        
        if (count == 7) {
            std::cout << "在 7 处中断循环" << std::endl;
            break;  // 完全退出循环
        }
        
        std::cout << "当前值: " << count << std::endl;
    }
    
    std::cout << "程序继续执行" << std::endl;
    return 0;
}

2. for 循环 - 传统计数器循环

基本语法

cpp 复制代码
for (初始化; 条件表达式; 迭代表达式) {
    // 循环体
}

示例1:基本 for 循环

cpp 复制代码
#include <iostream>

int main() {
    // 传统for循环
    std::cout << "0到4:" << std::endl;
    for (int i = 0; i < 5; ++i) {
        std::cout << i << " ";
    }
    std::cout << std::endl;
    
    std::cout << "1到10,步长为2:" << std::endl;
    for (int i = 1; i <= 10; i += 2) {
        std::cout << i << " ";
    }
    std::cout << std::endl;
    
    std::cout << "10到1,递减:" << std::endl;
    for (int i = 10; i > 0; --i) {
        std::cout << i << " ";
    }
    std::cout << std::endl;
    
    return 0;
}

示例2:C++17的初始化语句 for 循环

cpp 复制代码
#include <iostream>
#include <vector>

int main() {
    // C++17: 在for循环中使用初始化语句
    for (std::vector<int> vec{1, 2, 3, 4, 5}; auto& num : vec) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
    
    // 多个初始化语句
    for (int i = 0, j = 10; i < j; ++i, --j) {
        std::cout << "i=" << i << ", j=" << j << std::endl;
    }
    
    return 0;
}

3. 范围for循环 (Range-based for loop) - C++11起

基本语法

cpp 复制代码
for (元素类型 变量名 : 范围表达式) {
    // 循环体
}

示例1:遍历容器

cpp 复制代码
#include <iostream>
#include <vector>
#include <array>
#include <list>

int main() {
    // 遍历vector
    std::vector<int> vec = {1, 2, 3, 4, 5};
    std::cout << "Vector元素: ";
    for (int num : vec) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
    
    // 遍历array
    std::array<int, 5> arr = {10, 20, 30, 40, 50};
    std::cout << "Array元素: ";
    for (int num : arr) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
    
    // 遍历list
    std::list<std::string> names = {"Alice", "Bob", "Charlie"};
    std::cout << "List元素: ";
    for (const auto& name : names) {
        std::cout << name << " ";
    }
    std::cout << std::endl;
    
    return 0;
}

示例2:使用 auto 自动推导类型

cpp 复制代码
#include <iostream>
#include <vector>
#include <string>

int main() {
    std::vector<std::string> fruits = {"苹果", "香蕉", "橙子", "葡萄"};
    
    // 使用 auto(值拷贝)
    std::cout << "水果列表(值拷贝): ";
    for (auto fruit : fruits) {
        std::cout << fruit << " ";
    }
    std::cout << std::endl;
    
    // 使用 auto&(引用,避免拷贝)
    std::cout << "水果列表(引用): ";
    for (auto& fruit : fruits) {
        fruit = "水果: " + fruit;  // 可以修改元素
        std::cout << fruit << " ";
    }
    std::cout << std::endl;
    
    // 使用 const auto&(只读引用)
    std::cout << "修改后的水果列表: ";
    for (const auto& fruit : fruits) {
        std::cout << fruit << " ";
    }
    std::cout << std::endl;
    
    return 0;
}

示例3:遍历字符串

cpp 复制代码
#include <iostream>
#include <string>

int main() {
    std::string word = "C++";
    
    std::cout << "字符串中的字符: ";
    for (char ch : word) {
        std::cout << ch << " ";
    }
    std::cout << std::endl;
    
    // 使用引用修改字符串
    std::string message = "hello";
    for (char& ch : message) {
        ch = std::toupper(ch);  // 转为大写
    }
    std::cout << "大写: " << message << std::endl;
    
    return 0;
}

示例4:遍历初始化列表

cpp 复制代码
#include <iostream>

int main() {
    // 直接遍历初始化列表
    std::cout << "遍历初始化列表: ";
    for (int num : {1, 3, 5, 7, 9}) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
    
    // C++17: 结构化绑定遍历pair数组
    std::pair<int, std::string> pairs[] = {
        {1, "one"}, {2, "two"}, {3, "three"}
    };
    
    for (const auto& [number, name] : pairs) {
        std::cout << number << ": " << name << std::endl;
    }
    
    return 0;
}

4. while vs for 循环对比

特性 while 循环 for 循环 范围for循环
使用场景 不确定循环次数时 已知循环次数 遍历容器/数组
语法 while (条件) for (初始化; 条件; 递增) for (元素 : 容器)
条件控制 需要在循环体内更新 在循环头中控制 自动遍历
可读性 适合复杂条件 适合计数器 适合遍历
C++标准 所有版本 所有版本 C++11+

5. 嵌套循环

cpp 复制代码
#include <iostream>

int main() {
    // 嵌套循环 - 打印乘法表
    std::cout << "乘法表:" << std::endl;
    for (int i = 1; i <= 9; ++i) {
        for (int j = 1; j <= i; ++j) {
            std::cout << j << " × " << i << " = " 
                      << i * j << "\t";
        }
        std::cout << std::endl;
    }
    
    // 三维嵌套循环示例
    std::cout << "\n三维坐标示例:" << std::endl;
    for (int x = 0; x < 2; ++x) {
        for (int y = 0; y < 2; ++y) {
            for (int z = 0; z < 2; ++z) {
                std::cout << "(" << x << ", " << y << ", " << z << ") ";
            }
            std::cout << std::endl;
        }
    }
    
    return 0;
}

6. 基于范围的 for 循环的实现原理

cpp 复制代码
#include <iostream>
#include <vector>

// 自定义可迭代类型
class SimpleContainer {
private:
    int data[5] = {1, 2, 3, 4, 5};
    
public:
    // 迭代器类
    class Iterator {
    private:
        int* ptr;
        
    public:
        explicit Iterator(int* p) : ptr(p) {}
        
        int& operator*() { return *ptr; }
        Iterator& operator++() { ++ptr; return *this; }
        bool operator!=(const Iterator& other) const { return ptr != other.ptr; }
    };
    
    Iterator begin() { return Iterator(data); }
    Iterator end() { return Iterator(data + 5); }
};

int main() {
    SimpleContainer container;
    
    std::cout << "自定义容器的元素: ";
    for (int num : container) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
    
    // 范围for循环等价于:
    // {
    //     auto && __range = container;
    //     auto __begin = __range.begin();
    //     auto __end = __range.end();
    //     for (; __begin != __end; ++__begin) {
    //         int num = *__begin;
    //         // 循环体
    //     }
    // }
    
    return 0;
}

7. 算法替代循环(现代C++风格)

cpp 复制代码
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <ranges>  // C++20

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    
    // 传统循环
    std::cout << "传统循环: ";
    for (int num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
    
    // 使用算法:for_each
    std::cout << "使用for_each: ";
    std::for_each(numbers.begin(), numbers.end(), [](int num) {
        std::cout << num << " ";
    });
    std::cout << std::endl;
    
    // 使用算法:transform(类似Python的map)
    std::vector<int> squares;
    std::transform(numbers.begin(), numbers.end(), 
                   std::back_inserter(squares),
                   [](int n) { return n * n; });
    
    std::cout << "平方数: ";
    for (int sq : squares) {
        std::cout << sq << " ";
    }
    std::cout << std::endl;
    
    // 使用算法:copy_if(类似Python的filter)
    std::vector<int> evens;
    std::copy_if(numbers.begin(), numbers.end(),
                 std::back_inserter(evens),
                 [](int n) { return n % 2 == 0; });
    
    std::cout << "偶数: ";
    for (int even : evens) {
        std::cout << even << " ";
    }
    std::cout << std::endl;
    
    // C++20: 范围适配器
    std::cout << "C++20 范围适配器: ";
    auto even_squares = numbers 
        | std::views::filter([](int n) { return n % 2 == 0; })
        | std::views::transform([](int n) { return n * n; });
    
    for (int num : even_squares) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
    
    return 0;
}

8. 实用示例

示例1:猜数字游戏

cpp 复制代码
#include <iostream>
#include <random>
#include <limits>

void guess_number_game() {
    // 生成随机数
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<int> dist(1, 100);
    
    int number = dist(gen);
    int attempts = 0;
    constexpr int max_attempts = 7;
    
    std::cout << "欢迎来到猜数字游戏!\n";
    std::cout << "我想了一个1-100之间的数字,你有" 
              << max_attempts << "次机会猜。\n";
    
    while (attempts < max_attempts) {
        ++attempts;
        int remaining = max_attempts - attempts + 1;
        
        std::cout << "\n第" << attempts << "次尝试 (还剩" 
                  << remaining << "次): ";
        
        int guess;
        if (!(std::cin >> guess)) {
            std::cout << "请输入有效的数字!\n";
            std::cin.clear();
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            --attempts;  // 不计入有效尝试
            continue;
        }
        
        if (guess < number) {
            std::cout << guess << " 太小了\n";
        } else if (guess > number) {
            std::cout << guess << " 太大了\n";
        } else {
            std::cout << "恭喜!你在第" << attempts 
                      << "次猜中了数字 " << number << std::endl;
            return;
        }
    }
    
    std::cout << "\n游戏结束!数字是 " << number << std::endl;
}

int main() {
    guess_number_game();
    return 0;
}

示例2:斐波那契数列生成器

cpp 复制代码
#include <iostream>
#include <vector>

// 生成斐波那契数列
std::vector<int> fibonacci_sequence(int n) {
    if (n <= 0) return {};
    if (n == 1) return {0};
    if (n == 2) return {0, 1};
    
    std::vector<int> sequence = {0, 1};
    
    while (sequence.size() < static_cast<size_t>(n)) {
        int next = sequence.back() + sequence[sequence.size() - 2];
        sequence.push_back(next);
    }
    
    return sequence;
}

// 使用生成器模式(C++20协程简化版)
#include <coroutine>  // C++20
#include <memory>

struct FibonacciGenerator {
    struct promise_type;
    using handle_type = std::coroutine_handle<promise_type>;
    
    struct promise_type {
        int current_value;
        
        auto get_return_object() { 
            return FibonacciGenerator{handle_type::from_promise(*this)}; 
        }
        auto initial_suspend() { return std::suspend_always{}; }
        auto final_suspend() noexcept { return std::suspend_always{}; }
        void unhandled_exception() { std::terminate(); }
        
        auto yield_value(int value) {
            current_value = value;
            return std::suspend_always{};
        }
        void return_void() {}
    };
    
    handle_type coro_handle;
    
    FibonacciGenerator(handle_type h) : coro_handle(h) {}
    ~FibonacciGenerator() { if (coro_handle) coro_handle.destroy(); }
    
    bool move_next() {
        if (!coro_handle.done()) {
            coro_handle.resume();
            return !coro_handle.done();
        }
        return false;
    }
    
    int current_value() { return coro_handle.promise().current_value; }
};

FibonacciGenerator fibonacci_generator(int limit) {
    int a = 0, b = 1;
    
    for (int i = 0; i < limit; ++i) {
        co_yield a;
        int next = a + b;
        a = b;
        b = next;
    }
}

int main() {
    // 传统方式
    std::cout << "斐波那契数列前10项: ";
    auto fib = fibonacci_sequence(10);
    for (int num : fib) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
    
    // C++20协程方式
    std::cout << "使用生成器: ";
    auto gen = fibonacci_generator(10);
    while (gen.move_next()) {
        std::cout << gen.current_value() << " ";
    }
    std::cout << std::endl;
    
    return 0;
}

示例3:统计文本

cpp 复制代码
#include <iostream>
#include <string>
#include <cctype>
#include <map>
#include <algorithm>

void analyze_text(const std::string& text) {
    // 初始化计数器
    size_t char_count = 0;
    size_t word_count = 0;
    size_t sentence_count = 0;
    size_t vowel_count = 0;
    size_t consonant_count = 0;
    std::map<char, size_t> char_frequency;
    
    const std::string vowels = "aeiouAEIOU";
    
    // 遍历文本
    bool in_word = false;
    for (char ch : text) {
        ++char_count;
        
        // 统计字符频率
        ++char_frequency[ch];
        
        // 统计元音和辅音
        if (std::isalpha(static_cast<unsigned char>(ch))) {
            if (vowels.find(ch) != std::string::npos) {
                ++vowel_count;
            } else {
                ++consonant_count;
            }
        }
        
        // 统计单词
        if (std::isspace(static_cast<unsigned char>(ch)) || 
            std::ispunct(static_cast<unsigned char>(ch))) {
            if (in_word) {
                ++word_count;
                in_word = false;
            }
        } else {
            in_word = true;
        }
        
        // 统计句子
        if (ch == '.' || ch == '?' || ch == '!') {
            ++sentence_count;
        }
    }
    
    // 处理最后一个单词
    if (in_word) {
        ++word_count;
    }
    
    // 输出结果
    std::cout << "文本分析结果:" << std::endl;
    std::cout << "字符总数: " << char_count << std::endl;
    std::cout << "单词总数: " << word_count << std::endl;
    std::cout << "句子总数: " << sentence_count << std::endl;
    std::cout << "元音字母数: " << vowel_count << std::endl;
    std::cout << "辅音字母数: " << consonant_count << std::endl;
    
    // 计算平均单词长度
    if (word_count > 0) {
        double avg_word_length = static_cast<double>(char_count - 
            std::count_if(text.begin(), text.end(), 
                         [](char ch) { return std::isspace(static_cast<unsigned char>(ch)) || 
                                         std::ispunct(static_cast<unsigned char>(ch)); })) 
            / word_count;
        std::cout << "平均单词长度: " << avg_word_length << std::endl;
    }
    
    // 显示最常见的字符
    std::cout << "\n最常见字符: ";
    auto most_common = std::max_element(
        char_frequency.begin(), char_frequency.end(),
        [](const auto& a, const auto& b) { return a.second < b.second; }
    );
    
    if (most_common != char_frequency.end()) {
        std::cout << "'" << most_common->first << "' (出现" 
                  << most_common->second << "次)" << std::endl;
    }
}

int main() {
    std::string text = "C++ is a powerful programming language. "
                      "It's used for system software, game development, and more!";
    
    analyze_text(text);
    return 0;
}

现代C++循环的特点总结:

  1. 范围for循环:C++11引入,遍历容器更简洁
  2. auto类型推导:简化代码,提高可读性
  3. 结构化绑定:C++17引入,方便解构pair/tuple
  4. 初始化语句:C++17允许在if/switch/for中使用初始化语句
  5. 算法替代循环:使用STL算法更安全、更清晰
  6. C++20范围适配器:提供函数式编程风格
  7. 协程:C++20引入,支持生成器模式

最佳实践建议:

  1. 优先使用范围for循环遍历容器
  2. **使用const auto&**避免不必要的拷贝
  3. 考虑使用算法替代手写循环
  4. 利用结构化绑定简化代码
  5. 使用初始化语句限制变量作用域
  6. 注意迭代器失效问题(在循环中修改容器)

现代C++的循环结构既保留了传统的灵活性,又提供了现代的简洁性和安全性,使得代码更加清晰、高效。

相关推荐
程序员-周李斌8 小时前
ConcurrentHashMap 源码分析
java·开发语言·哈希算法·散列表·开源软件
JS_GGbond8 小时前
JavaScript入门学习路线图
开发语言·javascript·学习
quikai19819 小时前
python练习第一组
开发语言·python
BD_Marathon9 小时前
【JavaWeb】JS_JSON在客户端的使用
开发语言·javascript·json
还没想好取啥名9 小时前
C++11新特性(一)——原始字面量
开发语言·c++
谷粒.9 小时前
测试数据管理难题的7种破解方案
运维·开发语言·网络·人工智能·python
zzhongcy9 小时前
Java: HashMap 和 ConcurrentHashMap的区别
java·开发语言
寒山李白9 小时前
关于Python版本与supervisor版本的兼容性
windows·python·supervisord
c#上位机9 小时前
halcon获取多个独立连通域—connection
图像处理·c#·halcon