zoukankan      html  css  js  c++  java
  • circular_buffer

    编程有时需要使用定长的容器(fixed size container)。实现旋转容器可以像下面这样:

    std::vector<T> vec(size);
    vec[i % size] = newelem;

    但boost的circular_buffer提供更多功能,我们不需要重复造轮子了(DRY):

    #include <boost/circular_buffer.hpp>

        boost::circular_buffer<int> cb(3);
    
        // Insert threee elements into the buffer.
        cb.push_back(1);
        std::cout << "1 inserted, size:" << cb.size() << endl;
        std::cout << "latest is " << cb[cb.size() - 1] << endl;
    
        cb.push_back(2);
        std::cout << "2 inserted, size:" << cb.size() << endl;
        std::cout << "latest is " << cb[cb.size()-1] << endl;
    
        cb.push_back(3);
        std::cout << "3 inserted, size:" << cb.size() << endl;
        std::cout << "latest is " << cb[cb.size()-1] << endl;
    
        int a = cb[0];  // a == 1
        int b = cb[1];  // b == 2
        int c = cb[2];  // c == 3
    
        std::cout << "1st is" << a << endl;
        std::cout << "2nd is" << b << endl;
    
        // The buffer is full now, so pushing subsequent
        // elements will overwrite the front-most elements.
    
        cb.push_back(4);  // Overwrite 1 with 4.
        std::cout << "4 inserted, size:" << cb.size() << endl;
        std::cout << "latest is " << cb[cb.size()-1] << endl;
    
        cb.push_back(5);  // Overwrite 2 with 5.
        std::cout << "5 inserted, size:" << cb.size() << endl;
        std::cout << "latest is " << cb[cb.size()-1] << endl;
    
        // The buffer now contains 3, 4 and 5.
        a = cb[0];  // a == 3
        b = cb[1];  // b == 4
        c = cb[2];  // c == 5
        std::cout << "1st is" << a << endl;
    
    
        cb.pop_back();  // 5 is removed.
        cb.pop_front(); // 3 is removed.
        std::cout << "head and tail removed, size:" << cb.size() << endl;
        std::cout << "latest is " << cb[cb.size() - 1] << endl;
        // Leaving only one element with value = 4.
        int d = cb[0];  // d == 4
  • 相关阅读:
    【学习笔记】Python 3.6模拟输入并爬取百度前10页密切相关链接
    socket编程
    2.4.2电子书fb.c文件
    3.1 电子书框架
    文件浏览器及数码相框 -2.3.2-freetype_arm-2
    文件浏览器及数码相框 -2.3.2-freetype_arm-1
    文件浏览器及数码相框 -2.3.1freetype_pc
    文件浏览器及数码相框 -2.2-字符点阵及汉字库
    文件浏览器及数码相框 -2.1-字符编码
    文件浏览器及数码相框-1
  • 原文地址:https://www.cnblogs.com/scottgu/p/4259447.html
Copyright © 2011-2022 走看看