C++ format函数与STL容器的配合使用

发布时间:2024-10-11 10:08:38 作者:小樊
来源:亿速云 阅读:81

在C++中,std::format函数是一种类型安全且易于使用的方式来格式化字符串。它类似于Python的str.format或C#的string.Format,但它是C++标准库的一部分。std::format函数接受一个格式字符串和一个或多个参数,然后返回一个格式化后的字符串。

当与STL容器(如std::vectorstd::liststd::map等)配合使用时,std::format可以帮助你轻松地构建包含容器元素信息的字符串。以下是一些示例:

  1. 使用std::vector
#include <iostream>
#include <vector>
#include <format>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};
    std::string formatted_numbers = std::accumulate(numbers.begin(), numbers.end(), std::string{}, 
        [](const std::string& acc, int num) {
            return acc + std::to_string(num) + ", ";
        });
    formatted_numbers += "and " + std::to_string(numbers.back());
    std::cout << formatted_numbers << std::endl;
    return 0;
}

注意:在这个例子中,我使用了std::accumulate来将向量中的所有元素连接成一个字符串。然后,我使用std::format来添加“and”这个词以及向量的最后一个元素。但是,请注意,这个例子中的字符串拼接可能会导致性能问题,特别是在处理大量数据时。更好的方法是使用std::ostringstream,如下所示:

#include <iostream>
#include <vector>
#include <sstream>
#include <format>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};
    std::ostringstream oss;
    oss << std::accumulate(numbers.begin(), numbers.end(), std::string{}, 
        [](const std::string& acc, int num) {
            return acc + std::to_string(num) + ", ";
        });
    oss << "and " << std::to_string(numbers.back());
    std::cout << oss.str() << std::endl;
    return 0;
}
  1. 使用std::map
#include <iostream>
#include <map>
#include <format>

int main() {
    std::map<std::string, int> scores = {{"Alice", 90}, {"Bob", 85}, {"Charlie", 92}};
    std::string formatted_scores = "Scores:\n";
    for (const auto& pair : scores) {
        formatted_scores += std::format("  {} : {}\n", pair.first, pair.second);
    }
    std::cout << formatted_scores << std::endl;
    return 0;
}

在这个例子中,我使用std::format来构建一个包含映射中所有键值对的字符串。

推荐阅读:
  1. 总结C/C++语言中的头文件
  2. C++ STL编程是什么

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++

上一篇:格式化时间戳,C++ format的做法

下一篇:C++ format函数对代码重构的助力

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》