I want to wrap a vector<char>
with std::istream
(so reading the vector would be done through the istream
interface)
What's the way to do it?
You'd define a streambuf
subclass wrapping the vector
, and pass an instance of that to the istream constructor.
If the data does not change after construction, it is sufficient to set up the data pointers using streambuf::setg()
; the default implementation for the other members does the right thing:
template<typename CharT, typename TraitsT = std::char_traits<CharT> > class vectorwrapbuf : public std::basic_streambuf<CharT, TraitsT> { public: vectorwrapbuf(std::vector<CharT> &vec) { setg(vec.data(), vec.data(), vec.data() + vec.size()); } }; std::vector<char> data; // ... vectorwrapbuf<char> databuf(data) std::istream is(&databuf);
If you need anything more advanced than that, override the streambuf::underflow
method.
using Boost:
#include <boost/iostreams/stream.hpp> #include <boost/iostreams/device/array.hpp> using namespace boost::iostreams; basic_array_source<char> input_source(&my_vector[0], my_vector.size()); stream<basic_array_source<char> > input_stream(input_source);
or even simpler:
#include <boost/interprocess/streams/bufferstream.hpp> using namespace boost::interprocess; bufferstream input_stream(&my_vector[0], my_vector.size());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With