LoopQueue 快速实现
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include "gtest/gtest.h" #include "Util/LoopQueue/LoopQueue.h" struct LoopQueueTest : testing::Test { protected: LoopQueue loopQueue; }; TEST_F(LoopQueueTest, should_return_n_when_n_less_than_MAX_LOOP_QUEUE_LEN) { loopQueue.add(1); loopQueue.add(2); loopQueue.add(3); loopQueue.add(4); loopQueue.add(5); ASSERT_EQ(5, loopQueue.getLatest()); } TEST_F(LoopQueueTest, should_return_n_when_n_equals_MAX_LOOP_QUEUE_LEN) { loopQueue.add(1); loopQueue.add(2); loopQueue.add(3); loopQueue.add(4); loopQueue.add(5); loopQueue.add(6); ASSERT_EQ(6, loopQueue.getLatest()); } TEST_F(LoopQueueTest, should_return_n_when_n_more_than_MAX_LOOP_QUEUE_LEN) { loopQueue.add(1); loopQueue.add(2); loopQueue.add(3); loopQueue.add(4); loopQueue.add(5); loopQueue.add(6); loopQueue.add(7); loopQueue.add(8); loopQueue.add(9); ASSERT_EQ(9, loopQueue.getLatest()); }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#ifndef _INCL_DESIGN_PATTERNS_LoopQueue_H #define _INCL_DESIGN_PATTERNS_LoopQueue_H struct LoopQueue { LoopQueue(); void add(const int&); void print() const; int getLatest() const; private: int latestIndex; int len; private: enum { MAX_LOOP_QUEUE_LEN = 6 }; int elems[MAX_LOOP_QUEUE_LEN]; }; #endif
#include "Util/LoopQueue/LoopQueue.h" #include <iostream> LoopQueue::LoopQueue() : latestIndex(0), len(0) { } void LoopQueue::add(const int& elem) { elems[latestIndex] = elem; latestIndex = (latestIndex + 1) % MAX_LOOP_QUEUE_LEN; if (len != MAX_LOOP_QUEUE_LEN) { len++; } else { len = MAX_LOOP_QUEUE_LEN; } } int LoopQueue::getLatest() const { return elems[latestIndex - 1]; } void LoopQueue::print() const { int cursor, gap; for (int index = 0; index < len; ++index) { int gap = latestIndex - index - 1; int cursor = (gap < 0) ? (gap + len) : gap; std::cout << elems[cursor] << ","; } }