如何将一定数量的字符从文件复制到STL方式的向量? [英] How to copy a certain number of chars from a file to a vector the STL-way?
问题描述
如果我要将文件的内容复制到向量,我可以这样做:
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>());
我的问题是,如果我只想复制第一个 n chars?
My question is, how would I do this if I want to copy only the first n
chars?
编辑我可以编写我自己的 copy
,但是有没有办法只使用现有的组件?
Edit I could write my own version of copy
, but is there a way to do this using only existing components?
推荐答案
正如史蒂夫,这将需要 copy_n()
,由于疏忽, t在当前标准库中,但会在C ++ 1x中。你可以很容易地实现一个,这里是一个我相信是正确的:
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:
template<class InIt, class OutIt>
OutIt copy_n(InIt src, OutIt dest, size_t n)
{
if (!n) return dest;
*dest = *src;
while (--n)
*++dest = *++src;
return ++dest;
}
请注意 std :: copy_n code>假定输入迭代器能够提供
n
对象。当从文件读取时,这可能是有问题的。
Note that std::copy_n()
presumes the input iterator to be able to deliver n
objects. When reading from a file, this could be problematic.
缺少 std :: copy_n()
使用 std :: generate_n
。
template< typename InIt >
struct input_generator {
typedef std::iterator_traits<InIt>::value_type value_type;
input_generator(InIt begin, InIt end) begin_(begin), end_(end) {}
value_type operator()()
{
assert(it_ != end);
return *it_++;
}
Init begin_;
Init end_;
};
std::vector<char> buffer;
buffer.reserve(42);
std::generate_n( std::back_inserter(buffer)
, 42
, input_generator(std::istream_iterator<char>(file))
, input_generator(std::istream_iterator<char>()) );
但是,我看不到优于直接从文件读取 avakar显示。
这篇关于如何将一定数量的字符从文件复制到STL方式的向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!