【问题标题】:how to fill std::vector from istream using standard stl algorithms如何使用标准 stl 算法从 istream 填充 std::vector
【发布时间】:2015-06-04 12:51:47
【问题描述】:

有一个旧的遗留代码填充来自 istream 的向量, 向量中的对象在 ctor 中接受带有原始数据的字符串。

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

MyClass only ctor 看起来像这样:

MyClass(const std::string& data);

你有没有看到一些方法来避免写操作符>>或任何其他函数,并使用一些(?)标准算法来用构造的对象填充容器?可能会用 emplace 构造替换容器内值的指针。

顺便说一句,这段用 VC10 编译的代码不能正常工作,当我跨过 for 时看起来像无限循环。然而 istream(真的是 ifstream 那里)是一个小文件 ~200 行文本

【问题讨论】:

    标签: c++ stl containers stl-algorithm


    【解决方案1】:

    您可以使用std::transform。此代码需要 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); });
    

    【讨论】:

    • C++11/14 没问题。感谢您的解决方案
    猜你喜欢
    • 2018-08-16
    • 1970-01-01
    • 2021-04-12
    • 2016-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多