如何为std :: ostream_iterator设置前缀?

时间:2016-05-27 19:58:15

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

我想做这样的事情:

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功能。

1 个答案:

答案 0 :(得分:3)

你必须为operator<<课程重载std::ostream,以便它知道&#34;如何打印自定义类的实例。

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

#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;
}
相关问题