在previous question我问我如何阅读和舒适地将字符串矢量转换为整数或双精度的矢量。对和stringstream
现在我简单的扩展类型的载体的对向量的类型(考虑int
,double
,甚至std::string
,所有启用流类型)用冒号分隔。
例子:
time:5, length:10
应读为std::pair<std::string, unsigned int>
,像这样的东西:
// Here declare what to parse: a string and an uint, separated by a colon
get_vector<std::pair<std::string, unsigned int>>(s);
我如何写一个std::stringstream
操作员做的伎俩?
我无法弄清楚(或者说)我可以玩getline
(我的代码如下)。如果可能,我真的想离开get_vector
函数,因为它是。
谢谢!
template <class F, class S>
std::stringstream& operator >> (std::stringstream& in, std::pair<F, S> &out)
{
in >> out.first >> out.second;
return in;
}
template <class T>
auto get_vector(std::string s) -> std::vector<T>
{
std::vector<T> v;
// Vector of strings
auto tmp = split(s);
// Magic
std::transform(tmp.begin(), tmp.end(), std::back_inserter(v),
[](const std::string& elem) -> T
{
std::stringstream ss(elem);
T value;
ss >> value;
return value;
});
return v;
}
所以在你的代码中'elem'将是字符串''时间:5,长度:10“'? – NathanOliver
当你说你想离开get_vector函数时,你的意思是声明而不是定义,或者是你? –
@NathanOliver elem将会是“time:5”,因为原始字符串已被拆分为逗号分隔的组件。 – senseiwa