amigo421
amigo421

Reputation: 2541

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

Upvotes: 1

Views: 476

Answers (1)

TartanLlama
TartanLlama

Reputation: 65720

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

Upvotes: 6

Related Questions