可以像下面boost::format这样使用std::vector<std::string>。
std::vector<std::string> name = {"some", "name"};
boost::format("%s, %s") % name[0] % name[1];
Run Code Online (Sandbox Code Playgroud)
由于我有一个大向量,我想将它们一起使用而无需手动编写索引:
std::vector<std::string> name = {"some", "name"};
boost::format("%s, %s") % name;
Run Code Online (Sandbox Code Playgroud)
使用诸如boost::algorithm::join连接字符串之类的东西不是一个选择。有没有一种方法可以在不显式写入索引的情况下使用向量实现字符串格式化?
查看此示例:
#include <vector>
#include <string>
#include <iostream>
#include <boost/format.hpp>
auto format_vector(boost::format fmt, const std::vector<std::string> &v) {
for(const auto &s : v) {
fmt = fmt % s;
}
return fmt;
}
int main() {
std::vector<std::string> name = {"some", "name"};
std::cout << format_vector(boost::format("%s, %s"), name) << "\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
(https://godbolt.org/z/nGqW9h)
Operator%of format 在内部存储部分解析的字符串,并返回自身 - 因此它可以像常规使用一样链接起来。我们可以存储这个部分状态以与之循环操作。
尽管如此,您仍然需要注意%s格式字符串中的正确计数!
| 归档时间: |
|
| 查看次数: |
1254 次 |
| 最近记录: |