![](/img/trans.png)
[英]Passing a std::vector<char> constructed from istreambuf_iterator
[英]copying from a std::istreambuf_iterator<> to a std::vector<>
我有一個Visual Studio 2008 C ++應用程序,我想將流視為一組迭代器。
例如,如果我要在流上接收一個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 ) );
為此,我定義了一個派生自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
我無法弄清楚的是如何優雅地從一個byte
數組轉到一個WIN32_FIND_DATA
數組。 因為std::basic_streambuf<>
需要一個std::char_traits<>
模板參數,所以我的印象是它只能使用像char
或byte
這樣的內置類型,而不是像WIN32_FIND_DATA
這樣的結構。 正確?
有關如何使這項工作的任何建議?
謝謝,PaulH
istreambuf_iterator
在緩沖級別工作,它只是一個字節流。 如果你想處理結構,你可能想要使用istream_iterator
,並創建一個operator>>
來讀取WIN32_FIND_DATA
結構。 您還可以考慮為WIN32_FIND_DATA
創建/使用代理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.