[英]how to fill std::vector from istream using standard stl algorithms
there is an old legacy code which fills a vector from istream , the objects within the vector accept in ctor the string with raw data. 有一个旧的旧代码,它填充来自istream的向量,向量中的对象会使用原始数据接收字符串。
typedef std::vector<MyClass*> my_array;
std::istream& operator >> (std::istream& s, my_array& arr) {
if (s) {
std::istream_iterator<std::string> i_iter = s;
for(++i_iter; !s.eof(); arr.push_back(new MyClass(*i_iter++)));
}
return s;
}
where MyClass only ctor looks like: 其中MyClass仅ctor看起来像:
MyClass(const std::string& data);
do you see some way to avoid a writing operator>> or any other functions and use some (?) standard algorithm to fill the container up with just constructed objects? 您是否看到某种避免写操作符>>或任何其他函数的方法,并使用某些(?)标准算法将仅构造的对象填充到容器中? probably to replace the pointers on the values within a container with emplace contructing.
可能是通过位置结构替换容器内值的指针。
by the way, this code compiled with VC10 doesn't work properly, looks like infinite loop when I'm stepping over the for. 顺便说一句,用VC10编译的代码无法正常工作,当我跳过for时,它看起来像是无限循环。 however the istream (really this is ifstream there) is a small file ~200 lines of text
但是istream(实际上是ifstream)是一个小文件,大约200行文本
You could use std::transform
. 您可以使用
std::transform
。 This code requires C++11, if that won't work for you, you could change the lambda into a factory method and the alias declaration into a typedef
: 这段代码需要C ++ 11,如果对您不起作用,则可以将lambda更改为工厂方法,并将别名声明更改为
typedef
:
using it_type = std::istream_iterator<std::string>;
std::transform(it_type{std::cin}, it_type{},
std::back_inserter(a), [](const auto& a) { return new MyClass(a); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.