【发布时间】:2017-02-10 16:10:07
【问题描述】:
在previous question 中,我问过我如何读取字符串向量并将其轻松转换为整数或双精度向量。
现在我将简单类型的向量扩展为由冒号分隔的 pairs 类型(考虑 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将是字符串"time:5, length:10"? -
当您说要保留 get_vector 函数的原样时,您的意思是声明而不是定义,对吗?
-
@NathanOliver elem 将是 "time:5",因为原始字符串已被拆分为逗号分隔的组件。
-
@ChristianHackl 如果可能的话,我希望它保持原样,这就是为什么我认为运营商是必要的。
标签: c++ c++11 vector stringstream std-pair