在C++中,正则表达式和Lambda表达式都是强大的工具,分别用于不同的任务。下面是一些示例代码,展示了如何在C++中使用正则表达式和Lambda表达式。

使用正则表达式(C++11及以上)

在C++中,正则表达式功能由标准库中的<regex>头文件提供。以下是一个示例,展示了如何使用正则表达式来匹配和搜索字符串:

#include <iostream>
#include <regex>
#include <string>

int main() {
    // 要匹配的文本
    std::string text = "My email is example@example.com and my phone number is 123-456-7890.";

    // 定义匹配电子邮件地址的正则表达式
    std::regex email_regex(R"((\w+@\w+\.\w+))");
    std::smatch email_match;
    
    // 搜索文本中的电子邮件地址
    if (std::regex_search(text, email_match, email_regex)) {
        std::cout << "Found email: " << email_match[0] << std::endl;
    }

    // 定义匹配电话号码的正则表达式
    std::regex phone_regex(R"(\d{3}-\d{3}-\d{4})");
    std::smatch phone_match;

    // 搜索文本中的电话号码
    if (std::regex_search(text, phone_match, phone_regex)) {
        std::cout << "Found phone number: " << phone_match[0] << std::endl;
    }

    return 0;
}

在这个示例中,我们使用了std::regex来定义正则表达式,并使用std::regex_search在文本中搜索匹配的模式。

使用Lambda表达式(C++11及以上)

Lambda表达式是匿名函数的一种简洁语法。它们可以捕获作用域中的变量,并且经常用于标准库算法中。以下是一些示例,展示了如何使用Lambda表达式:

#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>

int main() {
    // 定义一个向量
    std::vector<int> numbers = {1, 2, 3, 4, 5};

    // 使用Lambda表达式计算向量的平方
    std::vector<int> squared_numbers;
    std::transform(numbers.begin(), numbers.end(), std::back_inserter(squared_numbers), [](int x) {
        return x * x;
    });

    std::cout << "Squared numbers: ";
    for (int num : squared_numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    // 使用Lambda表达式过滤偶数
    std::vector<int> even_numbers;
    std::copy_if(numbers.begin(), numbers.end(), std::back_inserter(even_numbers), [](int x) {
        return x % 2 == 0;
    });

    std::cout << "Even numbers: ";
    for (int num : even_numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    // 使用Lambda表达式计算向量的总和
    int sum = std::accumulate(numbers.begin(), numbers.end(), 0, [](int a, int b) {
        return a + b;
    });

    std::cout << "Sum of numbers: " << sum << std::endl;

    return 0;
}

在这个示例中,我们展示了如何使用Lambda表达式来进行各种操作:

  1. 使用std::transform将每个元素平方。
  2. 使用std::copy_if过滤偶数。
  3. 使用std::accumulate计算元素总和。

总结

正则表达式和Lambda表达式在C++中有着不同的用途:

  • 正则表达式主要用于模式匹配和文本处理。
  • Lambda表达式则用于定义匿名函数,并常用于STL算法中进行简洁的操作。

理解和掌握这两种工具,可以大大提高你的C++编程能力和代码简洁性。

05-15 02:45