1 #include <cstddef> 2 #include <vector> 3 4 template <class T> 5 class CircularVector 6 { 7 public: CircularVector(std::vector<T> & externalVec,size_t maxSizeIn)8 explicit CircularVector(std::vector<T>& externalVec, size_t maxSizeIn) : 9 vec(externalVec), maxSize(maxSizeIn) 10 {} 11 12 template <class... Args> emplace(Args &&...args)13 void emplace(Args&&... args) 14 { 15 if (maxSize == 0) 16 { 17 return; 18 } 19 if (vec.size() == maxSize) 20 { 21 vec.at(idx) = T(std::forward<Args>(args)...); 22 } 23 else 24 { 25 vec.emplace_back(std::forward<Args>(args)...); 26 } 27 idx = (idx + 1) == maxSize ? 0 : (idx + 1); 28 } 29 clear()30 void clear() 31 { 32 vec.clear(); 33 idx = 0; 34 } 35 clearAndResize(size_t newMaxSize)36 void clearAndResize(size_t newMaxSize) 37 { 38 clear(); 39 maxSize = newMaxSize; 40 } 41 isFull() const42 bool isFull() const 43 { 44 return vec.size() == maxSize; 45 } 46 begin() const47 typename std::vector<T>::const_iterator begin() const 48 { 49 return vec.begin(); 50 } 51 end() const52 typename std::vector<T>::const_iterator end() const 53 { 54 return vec.end(); 55 } 56 size() const57 size_t size() const 58 { 59 return maxSize; 60 } 61 62 private: 63 std::vector<T>& vec; 64 size_t maxSize = 0; 65 size_t idx = 0; 66 }; 67