如何将不同文件的内容写入向量以供 getline 进一步使用
我想将不同文件的内容保存到一个向量中: 矢量(0) = 内容文件1 矢量(1) = 内容文件2 ...
稍后,我需要逐行读出该向量的每个索引(getline):
getline(Vector(0), string myString)
当我在不同的站点上阅读时,我不能使用 vector
。
那么我该如何解决呢?
I want to save the content of different files to a vector:
Vector(0) = Content File1
Vector(1) = Content File2
...
Later on I need to read out from each index of this vector line by line (getline):
getline(Vector(0), string myString)
As I read on different sites, I can't use vector<istream> myVector
.
So how can I solve?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这取决于您要操作的数据的大小。我的两个样品已经过测试。
您可以使用处理一些原始指针的类
或 std::vector< std::向量< std::string > >。这是小文件的基本解决方案,但它确实有效。
It depends on the size of the data you want to manipulate. My two samples has been tested.
You can use a class which handles some raw pointers
Or a std::vector< std::vector< std::string > >. That's a basic solution for small files but it works.
iostream 不能放入任何 std 容器中。
也许您可以使用空指针数组来保存它们。
iostream cannot be put into any std container.
Maybe you can save them using a void pointer array.
需要明确的是,您是否想要存储文件句柄,然后稍后从文件中读取,或者将文件读入类似容器的字符串并将其存储在向量中?
如果您谈论的是后者并且文件是文本文件,则应该可以将它们读入
std::string
对象并以该形式存储它们。在std::string
中存储回车符等没有问题,但请记住,此解决方案可能无法扩展:如果您需要在您的存储中存储 4Gb+ 或 100,000 个文件,会发生什么情况向量?To be clear, are you wanting to store the file handles and then read from the files later or read the files into a string like container and store these in the vector?
If you're talking about the latter and the files are text files, it should be possible to read them into
std::string
objects and store them in that form. There's no problem in storing carriage return etc. in astd::string
but bear in mind that this solution may not be scaleable: What happens if you need to store a file that's 4Gb+ or 100,000 files in your vector?如果您想存储流向量,请考虑使用指针容器或智能指针向量,如下所示:
这只是示例代码 - 未经测试。
If you want to store a vector of streams, consider using a pointer container or a a vector of smart pointers, something like this:
This is just example code - untested.