C++ 如何在C+;中有效地将集合格式化为字符串+;?
我有一个程序,它有一个字符串(需要格式化),并从外部源获取元素集合。C++ 如何在C+;中有效地将集合格式化为字符串+;?,c++,string-formatting,stdvector,stdstring,fmt,C++,String Formatting,Stdvector,Stdstring,Fmt,我有一个程序,它有一个字符串(需要格式化),并从外部源获取元素集合。 字符串必须使用集合的元素格式化,这些元素是std::string。 我无法手动格式化字符串,例如: // Just examples sprintf(test, "%s this is my %s. This is a number: %d.", var[0], var[1], etc..); // i can't do this fmt::printf("%s this is my %s. This is a
字符串必须使用集合的元素格式化,这些元素是std::string。
我无法手动格式化字符串,例如:
// Just examples
sprintf(test, "%s this is my %s. This is a number: %d.", var[0], var[1], etc..); // i can't do this
fmt::printf("%s this is my %s. This is a number: %d.", var[0], var[1], etc..); // i can't do this (i also have fmt library)
std::string test = "%s this is a percentage: %d%%. This is a number: %d.";
// Output = "Hello this is a percentage: string5. This is a number: %d."
这是因为集合中的元素数是可变的。我想做的是尽可能高效地格式化字符串 代码如下:
std::string test = "%s this is my %s. This is a number: %d.";
std::vector<std::string> vec;
vec.push_back("Hello");
vec.push_back("string");
vec.push_back("5");
// String Formatting
std::size_t found;
for (auto i : vec)
{
found = test.find("%");
if (found != std::string::npos)
{
test.erase(found, 2);
test.insert(found, i);
}
}
std::cout << test;
总之:
使用多个元素格式化字符串最有效的方法是什么?即使不使用向量,但使用另一种结构。还是使用fmt或boost?(可能增压会降低效率)
我的开发环境是Visual Studio 2019。您可以使用{fmt}最近添加的
动态\u格式\u arg\u存储来实现这一点。
():
请注意,{fmt}使用
{}
而不是%
替换字段。请注意,VS2019仅支持C++14、17和20。没有可用于将其强制进入C++11模式的标志。getArgument(&str[0])
可能会损坏str
和内存,因为str
的大小和容量为0,因此无法写入。正如我所说,getArgument和checkArguments并不重要。我把它添加到代码中只是为了清楚。@Anyone97它们很重要。发布一个。@MaximeGroushkin只需对其进行注释,并手动插入元素,如示例所示。(向量推回(“你好”)等)。都一样。
#include <fmt/format.h>
int main() {
fmt::dynamic_format_arg_store<fmt::format_context> args;
args.push_back("Hello");
args.push_back("string");
args.push_back("5");
fmt::vprint("{} this is my {}. This is a number: {}.", args);
}
Hello this is my string. This is a number: 5.