簡體   English   中英

如何為std :: ostream_iterator設置前綴?

[英]How to set a prefix for std::ostream_iterator?

我想做這樣的事情:

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

您必須為std::ostream類重載operator<< ,以便它“知道”如何打印自定義類的實例。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM