2016-05-27 6 views
1

私はこのような何かをしたいと思います: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機能に触れたくない/触れることができないということです。

+1

あなたの研究は正しかった:

は、ここで私はあなたが達成したい理解して何の最小限の例です。あなたは正確に何をしようとしていますか? – jrok

+0

編集は@jrokを助けますか?否定的な答えが受け入れられるので、次の人は尋ねる必要はありません。 :) – gsamaras

+0

接頭辞を'Point_2'クラスに出力します。 – 0x499602D2

答えて

3

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; 
} 
関連する問題