C++20中的std::format

以下是C++20中std::format的核心用法详解及示例代码,结合官方特性和实际应用场景整理:


一、基础用法

  1. 自动类型推导
    使用{}作为占位符,自动推导参数类型:

    #include <format>
    #include <iostream>
    
    int main() {
        std::string str = std::format("int: {}, char: {}", 42, 'c');
        std::cout << str; // 输出:int: 42, char: c
    }
    
  2. 位置参数
    支持手动指定参数索引(从0开始),但不可与自动推导混用:

    std::cout << std::format("{1}比{0}快", "printf", "std::format");
    // 输出:std::format比printf快
    

二、格式控制符

  1. 数值格式化
    通过:附加格式规则,支持精度、进制等控制:

    // 浮点数保留3位小数
    std::cout << std::format("π≈{0:.3f}", 3.1415926535); // 输出:π≈3.142
    
    // 十六进制输出
    std::cout << std::format("255的十六进制:{0:#x}", 255); // 输出:0xff
    
  2. 对齐与填充
    指定宽度、对齐方式和填充字符:

    // 右对齐,宽度10,用*填充
    std::cout << std::format("{:*>10}", 42); // 输出:42
    
    // 居中对齐,宽度8
    std::cout << std::format("{:^8}", "C++20"); // 输出: C++20  
    

三、高级功能

  1. 运行时动态格式字符串
    使用std::vformat处理运行时生成的格式字符串:

    std::string fmt = "动态参数:{1}, {0}";
    auto args = std::make_format_args(3.14, "Pi");
    std::string str = std::vformat(fmt, args); // 输出:动态参数:Pi, 3.14
    
  2. 输出到迭代器
    避免内存拷贝,直接写入容器:

    std::vector<char> buffer;
    std::format_to(std::back_inserter(buffer), "缓冲区写入:{}", 100);
    
  3. 自定义类型支持
    通过特化std::formatter扩展自定义类型:

    struct Point { int x, y; };
    
    template <>
    struct std::formatter<Point> {
        auto parse(auto& ctx) { return ctx.begin(); }
        auto format(const Point& p, auto& ctx) {
            return std::format_to(ctx.out(), "({}, {})", p.x, p.y);
        }
    };
    
    std::cout << std::format("坐标:{}", Point{3, 5}); // 输出:坐标:(3, 5)
    

四、性能优势
std::format相比传统方法(如printf):

  • 类型安全:编译时检查参数类型,避免运行时崩溃 。
  • 高效实现:浮点格式化速度可达snprintf的10倍以上 。

五、编译要求
需启用C++20标准并包含头文件<format>

GCC/Clang编译命令示例
g++ -std=c++20 -O2 main.cpp
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

F-Halcon

浏览即鼓励

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值