创建一个ostream
出于教育原因,我正在尝试创建一个 C++ ostream。 我的测试将创建一个 ostream,其行为类似于 ofstream,只不过它不是写入文件,而是写入双端队列或向量容器。
I am trying to create a c++ ostream for educational reasons. My test will be creating an ostream that acts like a ofstream would except instead of writing to a file it would write to a deque or vector container.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
正如您所说,因为这是为了教育,我将向您展示我将如何做这样的事情。 否则,
stringstream
确实是正确的选择。听起来您想创建一个 Streambuf 实现,然后写入向量/双端队列。 像这样的事情(从我的另一个答案复制针对/dev/null Stream):
你可以像这样使用它:
如果你想有一个双端队列作为序列,你可以这样做:
或者类似的东西......好吧我还没有测试过它。 但也许这也是一件好事 - 所以如果它仍然包含错误,您可以尝试修复它们。
As it is for education, as you say, i will show you how i would do such a thingy. Otherwise,
stringstream
is really the way to go.Sounds like you want to create a streambuf implementation that then writes to a vector / deque. Something like this (copying from another answer of me that targeted a /dev/null stream):
You can use it like this:
If you want to have a deque as sequence, you can do so:
Or something similar... Well i haven't tested it. But maybe that's also a good thing - so if it contains still bugs, you can try fixing them.
使用 std::stringstream
Use std::stringstream
我只想指出,您不必为此编写类似 ostream 的类。 您可以使用适配器来实现您的目标。
例如,以下代码从 istream 读取并将每个元素插入到向量中:
I'll just remark that you don't have to write an ostream-like class for that. You can use an adapter to achieve your goal.
For example, this code reads from istream and inserts each element into a vector:
如果没有更多关于您想要做什么的详细信息,很难太具体,但您不想创建一个新的 ostream。 您想要做的是创建一个新类型的streambuf,并使用现有的ostream。
最简单的做法是继承 std::basic_filebuf<>,并重载sync() 和overflow() 方法以将元素添加到数据结构中。
Without more detail on what you want to do it is hard to be too specific, but you don't want to create a new ostream. What you want to do is create a new type streambuf, and use an existing ostream.
The easyist thing to do is to inherit from std::basic_filebuf<>, and overload the sync() and overflow() methods to add elements to your data structures.