Marcin Kalicinski wrote:
Is there a vectorstream class that implements the functionality similar to
std::stringstream but with std::vector, not std::string?
There is none in the standard C++ library but it is actually pretty
easy to create streams which read or write from a 'std::vector<char>'.
The class for reading from an 'std::vector<char>' would look
something like this:
class vectorinbuf:
public std::streambuf
{
public:
vectorinbuf(std::vector<char>& vec) {
this->setg(&vec[0], &vec[0], &vec[0] + vec.size());
}
};
class ivectorstream:
private virtual vectorinbuf,
public std::istream
{
public:
ivectorstream(std::vector<char>& vec):
vectorinbuf(vec),
std::istream(this)
{
}
};
The class for writing to a vector is a little bit more complex but
not much:
class vectoroutbuf:
public std::streambuf
{
public:
vectoroutbuf(std::vector<char>& vec):
m_vector(vec)
{
}
int overflow(int c)
{
if (c != std::char_traits<char>::eof())
m_vector.push_back(c);
return std::char_traits<char>::not_eof(c);
}
private:
std::vector<char> m_vector;
};
class ovectorstream:
private virtual vectoroutbuf,
public std::ostream
{
public:
ovectorstream(std::vector<char>& vec):
vectoroutbuf(vec),
std::ostream(this)
{
}
};
The behavior of the output stream is not tuned for performance,
though: writing of each individual character goes through a
virtual function call. This can be improved by some form of
buffering and synchronization. For example, the class could use
the initial size of the 'std::vector<char>' as a buffer instead
of appending to the vector. In this case, it would be necessary
to have a suitable call which adjusts the size of the vector to
the actual number of characters written.
--
<mailto:di***********@yahoo.com> <http://www.dietmar-kuehl.de/>
<http://www.eai-systems.com> - Efficient Artificial Intelligence