【问题标题】:format string with a variable size vector of arguments using fmt使用 fmt 格式化具有可变大小参数向量的字符串
【发布时间】:2022-12-29 23:31:24
【问题描述】:

我正在寻找一种使用可变大小的变量向量来格式化字符串的方法。怎么做?

我已经阅读了format string with a variable size vector of arguments (e.g. pass vector of arguments to std::snprintf)

我喜欢这个答案https://stackoverflow.com/a/57642429/20266935 的代码,但不幸的是,该代码不起作用,因为fmt::format 使用 constexpr 字符串。

所以我使用fmt::runtime修改了这个函数并编译,但我相信std::accumulate不能与fmt::format一起使用,因为它在一个循环中改变了字符串,一个{}被一个{}改变了,库没有像这样。

#include <fmt/core.h>
#include <numeric>
#include <iostream>
#include <vector>

std::string format_variable_size(const char* fmt, std::vector<int> args){
  return std::accumulate(
    std::begin(args),
    std::end(args),
    std::string{fmt},
    [](std::string toFmt, int arg){
      return fmt::format(toFmt, arg);
    }
  );
}

std::string runtime_format_variable_size(const char* fmt, std::vector<int> args){
  return std::accumulate(
    std::begin(args),
    std::end(args),
    std::string{fmt},
    [](std::string toFmt, int arg){
      return fmt::format(fmt::runtime(toFmt), arg);
    }
  );
}

int main()
{    
    std::vector<int> v = {1,2,3};
    std::cout << format_variable_size("[{}, {}, {}]\n", v); 
    std::cout << runtime_format_variable_size("[{}, {}, {}]\n", v); 
    return 0;
}

https://godbolt.org/z/337cGEh6d

有什么办法可以做到吗?

【问题讨论】:

  • 这似乎不可行,因为在编译时需要知道向量的大小。

标签: c++ fmt


【解决方案1】:

您可以使用实验性的 dynamic_format_arg_store API 来做到这一点:

#include <fmt/args.h>
#include <vector>

std::string runtime_format_variable_size(const char* fmt, std::vector<int> args){
  auto store = fmt::dynamic_format_arg_store<fmt::format_context>();
  for (int arg: args) store.push_back(arg);
  return fmt::vformat(fmt, store);
}

int main() {    
  auto v = std::vector<int>{1, 2, 3};
  auto s = runtime_format_variable_size("[{}, {}, {}]
", v);
  fmt::print("{}
", s);
}

这打印:

[1, 2, 3]

https://godbolt.org/z/7a79a4d8o

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-07
    • 1970-01-01
    • 2021-07-28
    • 1970-01-01
    • 1970-01-01
    • 2020-11-22
    相关资源
    最近更新 更多