We all know that the circular queue, the queue can address the shortcomings order: the order in the queue, the tail pointer when the team has been to the upper bound of the array, there is no longer operating into the team, but in fact there are empty positions in the array, which is called "false overflow "way to solve the false overflow.
General circulation is lined up to achieve full queue queue element can not be increased, and today we want to achieve is a special circular queue, you can add elements to achieve infinite, but there is a limit to take the time element, if the reach of elements do not take up.
To achieve the following:
ByteCirculate.h
#ifndef BYTE_CIRCULATE_H
#define BYTE_CIRCULATE_H
template<class T>
class circulate_queue
{
public:
circulate_queue(const circulate_queue &b) = delete;
circulate_queue& operator= (const circulate_queue &b) = delete;
circulate_queue(int size = 10)
{
_size = size;
_t = new T[_size];
_front = 0;
_end = -1;
}
~circulate_queue()
{
delete[]_t;
_t = nullptr;
}
void Add(T& t)
{
++_end;
if (_end - _front > _size)
{
++_front;
}
int i = _end % _size;
_t[i] = t;
}
T& Get(int index)
{
assert(index >= _front);
assert(index <= _end);
int i = index % _size;
return _t[i];
}
private:
T *_t;
int _size;
int _front;
int _end;
};
#endif
ByteCirculate_test.h
#pragma once
#include "ByteCirculate.h"
namespace Circulate
{
void start_test()
{
circulate_queue<int> *cicula = new circulate_queue<int>(20);
for (int i = 0; i < 1000; i++)
{
cicula->Add(i);
if (i > 10)
std::cout << cicula->Get(i - 10) << endl;
}
}
}
Second, the usefulness
When we need a certain amount of buffer zone can be used, has been added to the elements in the tail, the first team to take the elements
While team data to the end of the thread may soon, but there is a certain interval
The team's first uniform speed data processing thread
We can guarantee the security thread (guarantee index and taken at a certain interval index increases), but also can transmit the data to the data processing thread.