[英]copying from a std::istreambuf_iterator<> to a std::vector<>
I have a Visual Studio 2008 C++ application where I would like to treat a stream as a set of iterators. 我有一个Visual Studio 2008 C ++应用程序,我想将流视为一组迭代器。
For example, if I were to receive an array of WIN32_FIND_DATA structures over the stream, I would like to be able to do something like this: 例如,如果我要在流上接收一个WIN32_FIND_DATA结构数组,我希望能够做到这样的事情:
IStreamBuf< WIN32_FIND_DATA > sb( stream );
std::vector< WIN32_FIND_DATA > buffer;
std::copy( std::istreambuf_iterator< WIN32_FIND_DATA >( &sb ),
std::istreambuf_iterator< WIN32_FIND_DATA >(),
std::back_inserter( buffer ) );
To accomplish this, I've defined a class derived from std::basic_streambuf<>
: 为此,我定义了一个派生自
std::basic_streambuf<>
:
template< typename T >
class IStreamBuf : public std::basic_streambuf< byte >
{
public:
IStreamBuf( IStream* stream ) : stream_( stream )
{
};
protected:
virtual traits_type::int_type underflow()
{
DWORD bytes_read = 0;
HRESULT hr = stream_->Read( &buffer_, sizeof( T ), &bytes_read );
if( FAILED( hr ) )
return traits_type::eof();
traits_type::char_type* begin =
reinterpret_cast< traits_type::char_type* >( &buffer_ );
setg( begin, begin, begin + bytes_read );
return traits_type::to_int_type( *gptr() );
};
private:
// buffer to hold current item of type T
T buffer_;
// stream used to receive data
IStream* stream_;
}; // class IStreamBuf
What I can't figure out is how to gracefully go from an array of byte
s to an array of WIN32_FIND_DATA
s. 我无法弄清楚的是如何优雅地从一个
byte
数组转到一个WIN32_FIND_DATA
数组。 Because std::basic_streambuf<>
requires a std::char_traits<>
template parameter, I'm under the impression that it can only use built-in types like char
or byte
, not a structure like WIN32_FIND_DATA
. 因为
std::basic_streambuf<>
需要一个std::char_traits<>
模板参数,所以我的印象是它只能使用像char
或byte
这样的内置类型,而不是像WIN32_FIND_DATA
这样的结构。 Correct? 正确?
Any suggestions on how to make this work? 有关如何使这项工作的任何建议?
Thanks, PaulH 谢谢,PaulH
An istreambuf_iterator
works at the buffer level, where it's just a stream of bytes. istreambuf_iterator
在缓冲级别工作,它只是一个字节流。 If you want to deal with structures, you probably want to use an istream_iterator
instead, and create an operator>>
to read the WIN32_FIND_DATA
structures. 如果你想处理结构,你可能想要使用
istream_iterator
,并创建一个operator>>
来读取WIN32_FIND_DATA
结构。 You might also consider creating/using a proxy for the WIN32_FIND_DATA
. 您还可以考虑为
WIN32_FIND_DATA
创建/使用代理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.