简体   繁体   中英

How to set a prefix for std::ostream_iterator?

I would like to do something like this:

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

Is this even possible? I worry because my research says no, hope it was broken. :)


The goal is to take the convex hull points produced by CGAL and write them in a file like this:

p 2 0
p 0 0
p 5 4

with this code:

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

and the problem is that I do not want/can touch the CGAL function.

You have to overload the operator<< for the std::ostream class, so that it "knows" how to print an instance of your custom class.

Here is a minimal example of what I understand you want to accomplish:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM