Effective Circular List

I want a simple but effective round buffer / queue. If I use std::vector, I have to do this:

if ( v.size() >= limit ) {
    std::vector<int> it = v.begin();
    v.insert( it, data );
    v.erase( it+1 );
}

Is there a simpler solution?

+5
source share
4 answers

You want to keep the buffer size by overwriting the old elements. Just rewrite the old ones over time. If you want to deal with the case when nItems <limit, then you will need to deal with this, this is just a simple example of using modulo to insert into a fixed-size buffer.

std::vector<int> data(10);

for (int i = 0 ; i < 100 ; ++i)
{
    data[i%10] = i;
}

for (std::vector<int>::const_iterator it = data.begin() ; it !=data.end(); ++it)
{
     std::cout << *it << std::endl;
}

This paste method will save the last 10 items in the buffer.

+8
source

A std::listmay be an easier alternative to creating a list than std::vector. There also std::queue.

, , , , ?

+2

Try std :: deque. The interface is similar to using std :: vector, but inserting and deleting from the beginning and the end are more efficient.

0
source

In c++11for a fixed-size alternative, you should use std::array:

const unsigned int BUFFER_SIZE = 10;
std::array<int, BUFFER_SIZE> buffer; // The buffer size is fixed at compile time.
for (i = 0; i < 100; ++i) {
    buffer[i%10] = i;
}
0
source

All Articles