C ++:包装向量< char>与istream [英] C++: Wrapping vector<char> with istream

查看:123
本文介绍了C ++:包装向量< char>与istream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用向量< char> 包装 std :: istream 通过 istream 界面完成)



这是什么方法?


< div定义 c> c> c> c> c> c>,并将其实例传递给istream构造函数。



如果数据在构造之后不改变,则使用 streambuf :: setg();其他成员的默认实现方式是正确的:

  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 。尺寸()​​);
}
};

std :: vector< char>数据;
// ...
vectorwrapbuf< char> databuf(data)
std :: istream is(& databuf);

如果你需要更高级的,覆盖 streambuf :: underflow 方法。


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.

这篇关于C ++:包装向量&lt; char&gt;与istream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆