如何以 STL 方式将文件中一定数量的字符复制到向量?
如果我想将文件的内容复制到向量中,我可以这样做:
std::ifstream file("path_to_file");
std::vector<char> buffer(std::istream_iterator<char>(file),
std::istream_iterator<char>());
我的问题是,如果我只想复制前 n 个字符,我该怎么做?
编辑我可以编写自己的copy
,但是有没有办法仅使用现有组件来做到这一点?
If I want to copy the contents of a file to a vector, I can do it like that:
std::ifstream file("path_to_file");
std::vector<char> buffer(std::istream_iterator<char>(file),
std::istream_iterator<char>());
My question is, how would I do this if I want to copy only the first n
chars?
Edit I could write my own version of copy
, but is there a way to do this using only existing components?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
正如 Alexander 指出的,最快的方法是
在 C++0x 中,您可以使用
buffer.data()
而不是&buffer[0]
;如果n == 0
,后者具有未定义的行为。As Alexander points out, the fastest way would be
In C++0x, you can use
buffer.data()
instead of&buffer[0]
; the latter has undefined behavior ifn == 0
.正如 史蒂夫,这需要< code>copy_n(),由于疏忽,它不在当前的标准库中,但将在 C++1x 中。您可以轻松地自己实现一个,这是我认为正确的一个:
请注意,
std::copy_n()
假定输入迭代器能够传递n
对象。从文件读取时,这可能会出现问题。如果没有
std::copy_n()
,您可以使用std::generate_n
。但是,我不认为这比直接从文件中读取 avakar 显示。
As was noted by Steve, this would need
copy_n()
, which, due to an oversight, isn't in the current standard library, but will be in C++1x. You can implement one yourself easily, here's one I believe to be correct:Note that
std::copy_n()
presumes the input iterator to be able to delivern
objects. When reading from a file, this could be problematic.Absent of
std::copy_n()
, you could usestd::generate_n
.However, I don't see this as an advantage over reading directly from the file as avakar showed.
“STL方式”是使用
copy_n
,它是STL中的,但不是C++标准中的。The "STL way" is to use
copy_n
, which is in the STL but not the C++ standard.这可能不是最漂亮或最快的方法,但这是我会做的。
It may not be the prettiest or quickest way, but it is how I would do it.
感谢@sbi,我忘记了
generate_n
。file
内的streambuf
有一个函数snextc
,一旦其隐式this<,它就会返回下一个字符,将其限定为生成器函数。 /code> 参数已绑定。
对于
vector
,直接读取即可。这对于deque
或其他什么都有好处。Credit due to @sbi, I forgot about
generate_n
.The
streambuf
insidefile
has a functionsnextc
which returns the next character, qualifying it as a generator function, once its implicitthis
argument is bound.For
vector
, just read directly. This is good fordeque
or whatever.