我有一个参数包,如下所示:
<int, long, string, double>
并且像字符串这样
"100 1000 hello 1.0001"
如何解析这些数据并将它们打包成std::tuple<int, long, string, double>?
一种方法是使用 std::apply
来展开 tuple
的元素,然后使用 istringstream
提取格式化数据并将其赋值给该元素。
#include <string>
#include <tuple>
#include <sstream>
int main() {
std::string s = "100 1000 hello 1.0001";
std::tuple<int, long, std::string, double> t;
auto os = std::istringstream{s};
std::apply([&os](auto&... x) {
(os >> ... >> x);
}, t);
}
std::string::find
和std::string::substr
等函数来实现。然后你可以按需转换每个值。对于字符串转整数,使用std::stoi
。对于字符串转双精度浮点数,使用std::stod
。 - Michael Sohnen