将固定数量的字节复制到std :: deque <char> </char>中

时间:2014-06-26 14:47:15

标签: c++ std

我正在创建一个缓冲从std::cin读取的二进制数据的类;我需要一些限制 能够通过流回溯。 更详细地说,当我从流中获得read n个字节时,我希望能够回放到 流中的n个字节。

目前,我通过附加单个字符附加到缓冲区 到std::deque,但我希望有更好的方法来复制 从std::istreamstd::deque的数据块。

基本上有一种方法可以改进(删除?)while循环 下面的load功能?

目前我有:

#include<algorithm>
#include<deque>

class BufferedStdIn{
public:

BufferedStdIn(): m_buffer(), m_cursor(0){
}

// copy data out from my internal buffer to the client's array
// format dictated by external interface requirement
void read(char* dest, size_t n){
    load(n)
    std::copy( m_buffer.begin(), m_buffer.begin()+n, dest );
    m_cursor+=n;
}

// Go backwards in the stream; return the number of bytes moved.
// @retval < input arg n indicates that we can't rewind as far as asked for
size_t rewind(size_t n){
    int final_pos=m_cursor-n;
    if( final_pos < 0 ){
        // can't go as far as the client wants, just go back to start of my buffer
        size_t moved=m_cursor;
        m_cursor=0;
        return moved;
    }
    else{ // can do what client wants
        m_cursor=final_pos;
        return n;
    }
}

void load(n){
    m_buffer.erase( m_buffer.begin(), m_buffer.begin()+m_cursor);
    m_cursor=0;
    while( m_buffer.size()<n){
        char c;
        std::cin.get(c);
        m_buffer.push_back(c);
    }
}

// SNIP: other functions that let clients look at m_buffer

std::deque<char> m_buffer;
size_t m_cursor;


}

1 个答案:

答案 0 :(得分:1)

可能效率不高,但更短:

void load(size_t n)
{
    m_buffer.erase( m_buffer.begin(), m_buffer.begin()+m_cursor);
    m_cursor=0;
    if(m_buffer.size() < n)
        std::copy_n(std::istream_iterator<char>(std::cin), n - m_buffer.size(), std::back_inserter(m_buffer));
}