简体   繁体   中英

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.

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(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. however the istream (really this is ifstream there) is a small file ~200 lines of text

You could use 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 :

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); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM