如何为 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;
}
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 在C++/Linux中设置单调时钟的一些技巧
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 嵌套在类中时无法设置成员数据
- 需要帮助设置在C++中使用的Potrace
- 如何在自删除后将对象设置为nullptr
- 将指针设置为"nullptr"并不能防止双重删除?
- 如何在Ubuntu中使用cmake设置qt4
- ld:bind_at_load和-bitcode_bundle(Xcode设置ENABLE_bitcode=YES)不能
- 如何在boost beast http请求中设置http头
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 如何将这个C++哈希表转换为动态扩展和收缩,而不是使用硬设置的最大值
- 为什么文件名被设置为一个点,而不是在读取矢量中的文件名时
- 如何在24位SDL_Surface上设置像素的颜色
- std::设置自定义比较器
- 如何设置一个范围来提取我想要获得的信息
- 如何在C/C++中用FD_set Unix设置套接字文件描述符
- 通过选项卡的文本设置QTabWidget顺序
- 将特征矩阵的向量设置为0
- 我可以检测和更改 gcc/g++ 中结构的当前数据对齐设置吗?