Search code examples
c++boostcircular-buffer

How to tell the current 'write position' of a Boost Circular Buffer to enable accessing a previously stored value


I want to access a value in a Boost Circular Buffer that is, for example, 5 positions 'in the past'. So, imagine I am now writing a value '7' to a previous stream of integers:

3, 5, 6, 9, 2, 8, 6

Therefore I have now:

7, 3, 5, 6, 9, 2, 8, 6

I want the '2' since that is 5 positions in the past. How do I get that?

In other words, what is the current 'write index'?

I think that I might need to use boost::circular_buffer<double>::const_iterator but I'm not sure.


Solution

  • I'm not sure I understand correctly, but your worries about modulo indexing seem overly anxious to me. The whole purpose of a circular buffer abstraction is to hide the index arithmetics from the caller, if you ask me.

    I'd be thoroughly disappointed in the library design if Boost would let this implementation detail leak out¹

    Here's a simple demo that seems to be what you want:

    Live On Coliru

    #include <iostream>
    #include <boost/circular_buffer.hpp>
    
    int main() {
        boost::circular_buffer<int> cb(10); // [tag:cb-so-fixedsize] obviously
    
        for (int msg : { 3, 5, 6, 9, 2, 8, 6, 7 }) {
            cb.push_back(msg);
        }
    
        // should be 2
        std::cout << "t0-5: " << cb[4] << "\n";
        std::cout << "t0-5: " << *std::next(cb.begin(), 4) << "\n";
    
        // should be 9
        std::cout << "t0-5: " << cb[3] << "\n";
        std::cout << "t0-5: " << *std::next(cb.begin(), 3) << "\n";
    
        while (!cb.empty()) {
            std::cout << cb.front() << " ";
            cb.pop_front();
        }
    }
    

    Prints

    t0-5: 2
    t0-5: 2
    t0-5: 9
    t0-5: 9
    3 5 6 9 2 8 6 7 
    

    ¹ I'm well aware that the implementation detail is implied by the name "circular", but hey. Many data structures in the standard library and alike have slightly confusing names