Szymon Dompke | 3eb5686 | 2021-09-20 15:32:04 +0200 | [diff] [blame] | 1 | #include <vector> |
| 2 | |
| 3 | template <class T> |
| 4 | class CircularVector |
| 5 | { |
| 6 | public: |
Krzysztof Grobelny | 493e62e | 2022-02-14 10:55:50 +0100 | [diff] [blame] | 7 | explicit CircularVector(std::vector<T>& externalVec, size_t maxSizeIn) : |
| 8 | vec(externalVec), maxSize(maxSizeIn) |
Szymon Dompke | 3eb5686 | 2021-09-20 15:32:04 +0200 | [diff] [blame] | 9 | {} |
| 10 | |
| 11 | template <class... Args> |
| 12 | void emplace(Args&&... args) |
| 13 | { |
| 14 | if (maxSize == 0) |
| 15 | { |
| 16 | return; |
| 17 | } |
| 18 | if (vec.size() == maxSize) |
| 19 | { |
| 20 | vec.at(idx) = T(std::forward<Args>(args)...); |
| 21 | } |
| 22 | else |
| 23 | { |
| 24 | vec.emplace_back(std::forward<Args>(args)...); |
| 25 | } |
| 26 | idx = (idx + 1) == maxSize ? 0 : (idx + 1); |
| 27 | } |
| 28 | |
| 29 | void clear() |
| 30 | { |
| 31 | vec.clear(); |
| 32 | idx = 0; |
| 33 | } |
| 34 | |
| 35 | void clearAndResize(size_t newMaxSize) |
| 36 | { |
| 37 | clear(); |
| 38 | maxSize = newMaxSize; |
| 39 | } |
| 40 | |
| 41 | bool isFull() const |
| 42 | { |
| 43 | return vec.size() == maxSize; |
| 44 | } |
| 45 | |
| 46 | typename std::vector<T>::const_iterator begin() const |
| 47 | { |
| 48 | return vec.begin(); |
| 49 | } |
| 50 | |
| 51 | typename std::vector<T>::const_iterator end() const |
| 52 | { |
| 53 | return vec.end(); |
| 54 | } |
| 55 | |
Krzysztof Grobelny | a8182be | 2022-07-04 11:26:20 +0200 | [diff] [blame] | 56 | size_t size() const |
| 57 | { |
| 58 | return maxSize; |
| 59 | } |
| 60 | |
Szymon Dompke | 3eb5686 | 2021-09-20 15:32:04 +0200 | [diff] [blame] | 61 | private: |
Krzysztof Grobelny | 493e62e | 2022-02-14 10:55:50 +0100 | [diff] [blame] | 62 | std::vector<T>& vec; |
Szymon Dompke | 3eb5686 | 2021-09-20 15:32:04 +0200 | [diff] [blame] | 63 | size_t maxSize = 0; |
| 64 | size_t idx = 0; |
Szymon Dompke | 3eb5686 | 2021-09-20 15:32:04 +0200 | [diff] [blame] | 65 | }; |