简体   繁体   English

如何使用标准stl算法从istream填充std :: vector

[英]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.

相关问题 如何从 std::vector 转换<float>到 std::istream?</float> - How to convert from std::vector<float> to std::istream? 使用STL算法进行向量处理 - Vector manipulation using STL algorithms 在模板化类中使用STL算法(特别是std :: sort) - Using STL algorithms (specifically std::sort) from within a templated class 使用带有std :: fill等算法的emplace - Using emplace with algorithms such as std::fill 为什么STL算法的指针要比std :: vector迭代器快得多? - Why are STL algorithms much faster with pointers than std::vector iterators? 如何在使用算法保持原始顺序的同时从未排序的 std::vector 中删除重复项? - How to remove duplicates from unsorted std::vector while keeping the original ordering using algorithms? 如何在不使用标准算法的情况下将c元素添加到排序向量中? - How to add c element in sorted vector without using standard algorithms? 如何使用 STL 算法将整数向量转换为字符串向量? - How can I convert a vector of ints to be a vector of strings using STL algorithms? 如何从std :: istream中读取(使用operator &gt;&gt;)? - How can I read from an std::istream (using operator>>)? 如何转换 std::vector<T> 到对 std::vector 的向量<std::pair<T,T> &gt; 使用 STL 算法? - How can I convert std::vector<T> to a vector of pairs std::vector<std::pair<T,T>> using an STL algorithm?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM