[英]vector of string to istringstream
I want to populate a istringstream object with content from vector of strings. 我想用字符串向量中的内容填充istringstream对象。 Is there an elegant way to do this?
有没有一种优雅的方法可以做到这一点? I am doing the following now, which is not nice:
我现在正在做以下事情,这不是很好:
vector<string> vec = {"apple", "banana", "dog", "cat"};
string one_str;
for (string s: vec) {
one_str += s + " ";
}
istringstream iss(one_str);
Note that I want to populate istringstream and not stringstream or ostringstream 请注意,我要填充istringstream而不是stringstream或ostringstream
You can't make an istringstream
read from any external source: it always makes a copy, even of a single string. 您不能使
istringstream
从任何外部源读取:它总是复制,甚至是单个字符串。 You can, however, make a stream that reads from any data source by making your own streambuf
class and making an istream
from a pointer to an instance of it. 但是,您可以通过创建自己的
streambuf
类并从指向其实例的指针中创建istream
来创建从任何数据源读取的流。 A minimal version needs only one method overridden: 最低版本仅需要覆盖一种方法:
#include<streambuf>
#include<string>
#include<vector>
struct stringsbuf : std::streambuf {
stringsbuf(const std::string *b,const std::string *e) : ss(b),se(e) {}
stringsbuf(const std::vector<std::string> *v) : // pointer vs. temporaries
ss(&v->front()),se(ss+v->size()) {}
int_type underflow() override {
while(ss!=se) {
auto &s=*ss++;
if(s.empty()) continue;
char *p=const_cast<char*>(s.data());
setg(p,p,p+s.size());
return *p;
}
return traits_type::eof();
}
private:
const std::string *ss,*se; // next string to load, and past-the-end string
};
This could of course be made more efficient and featureful by adding one or more of xsgetn
, seekoff
, seekpos
, and showmanyc
. 当然,可以通过添加
xsgetn
, seekoff
, seekpos
和showmanyc
一个或多个来提高效率和showmanyc
。 It could also be made generic (not only on character type, but also by accepting any string
-valued iterators). 也可以使其通用(不仅在字符类型上,而且可以通过接受任何
string
值的迭代器)。
The elegance here lies in the fact that no concatenated string is ever constructed (except perhaps by the client that reads from an istream
based on a stringsbuf
). 这里的优雅之处在于,实际上没有构造任何串联的字符串(也许由基于
stringsbuf
从istream
读取的客户端stringsbuf
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.