Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost Circular Buffer push_back inserts data at front

Tags:

c++

boost

I have below code:

#include "boost/circular_buffer.hpp"

int main()
{
    // Create a circular buffer with a capacity for 3 integers.
    boost::circular_buffer<int> cb(3);

    // Insert threee elements into the buffer.
    cb.push_back(1);


    int a = cb[0];  // a == 1

}

As per documentation push_back API means "Insert a new element at the end of the circular_buffer" - then how cb[0] is 1? Shouldn't cb[2] should store value 1?

=======================================UPDATE=============================

// Insert threee elements into the buffer.
cb.push_front(11);
cb.push_back(2);
cb.push_back(3);

int a = cb[0];  // a == 11
int b = cb[1];  // b == 2
int c = cb[2];  // c == 3

It seems that in case there are 0 elements in an buffer it takes up the first but if the same has one then it puts it at the end

like image 317
Programmer Avatar asked Jan 30 '26 03:01

Programmer


1 Answers

No. The buffer has capacity for three elements, but only contains one.

When you do your first push_back, you push to the end of a series of zero elements. So the new element becomes the first.

If you want to fill it up completely on construction, you can do that! Just like you would with a vector:

boost::circular_buffer<int> cb(3, 0);

But then, your first push_back will still alter cb[0], because it's a circular buffer! That means it wraps around to the front when full. cb[3] is out of range. There is no cb[3].

like image 123
Lightness Races in Orbit Avatar answered Feb 01 '26 18:02

Lightness Races in Orbit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!