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)
{
while (n--)
*dest++ = *src++;
return dest;
}
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.
Absent of std::copy_n()
, you could use 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>()) );
However, I don't see this as an advantage over reading directly from the file as avakar showed.