Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Wrapping vector<char> with istream

Tags:

c++

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?

like image 693
GabiMe Avatar asked Jan 11 '12 06:01

GabiMe


2 Answers

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.

like image 121
Simon Richter Avatar answered Sep 23 '22 14:09

Simon Richter


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()); 
like image 28
ZunTzu Avatar answered Sep 23 '22 14:09

ZunTzu