【问题标题】:How to set a prefix for std::ostream_iterator?如何为 std::ostream_iterator 设置前缀?
【发布时间】:2016-05-27 19:58:15
【问题描述】:

我想做这样的事情:

std::ofstream ch("ch_out.txt");
std::ostream_iterator< cgal_class >  out( "p ", ch, "\n" );

这甚至可能吗?我担心,因为我的研究说不,希望它被打破了。 :)


目标是获取 CGAL 生成的凸包点,并将它们写入文件中,如下所示:

p 2 0
p 0 0
p 5 4

使用此代码:

std::ofstream ch("ch_out.txt");
std::ostream_iterator< Point_2 >  out( "p ", ch, "\n" );
CGAL::ch_graham_andrew( in_start, in_end, out );

问题是我不想/不能触摸 CGAL 功能。

【问题讨论】:

  • 您的研究是正确的。你到底想做什么?
  • 编辑帮助@jrok。否定的答案将被接受,这样下一个人就不必问了。 :)
  • 输出Point_2类中的前缀。
  • 我认为最简单的方法是编写自己的迭代器。
  • @0x499602D2 是的,或者那个:)

标签: c++ c++11 stl iterator ostream


【解决方案1】:

您必须为std::ostream 类重载operator&lt;&lt;,以便它“知道”如何打印您的自定义类的实例。

这是我理解您想要完成的一个最小示例:

#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>

class MyClass {
 private:
  int x_;
  int y_;
 public:
  MyClass(int x, int y): x_(x), y_(y) {}

  int x() const { return x_; }
  int y() const { return y_; }
};

std::ostream& operator<<(std::ostream& os, const MyClass &c) {
  os << "p " << c.x() << " " << c.y();
  return os;
}

int main() {
  std::vector<MyClass> myvector;
  for (int i = 1; i != 10; ++i) {
    myvector.push_back(MyClass(i, 2*i));
  }

  std::ostream_iterator<MyClass> out_it(std::cout, "\n");
  std::copy(myvector.begin(), myvector.end(), out_it);

  return 0;
}

【讨论】:

    猜你喜欢
    • 2017-09-19
    • 2015-01-10
    • 2020-11-25
    • 2014-10-06
    • 2019-11-13
    • 2015-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多