|
|
@@ -114,7 +114,7 @@ public:
|
|
|
class Iterator
|
|
|
{
|
|
|
public:
|
|
|
- Iterator(RingQueueManualMutex<T>* queue) : m_ptr(queue), m_index(m_ptr->m_front) {}
|
|
|
+ // Iterator(RingQueueManualMutex<T>* queue) : m_ptr(queue), m_index(m_ptr->m_front) {}
|
|
|
Iterator(RingQueueManualMutex<T>* queue, long index) : m_ptr(queue), m_index(index) {}
|
|
|
|
|
|
T& operator*() {
|
|
|
@@ -124,16 +124,15 @@ public:
|
|
|
}
|
|
|
return m_ptr->m_queue[m_index];
|
|
|
}
|
|
|
- T* operator->() {
|
|
|
+ T* operator->() {
|
|
|
if(m_index == -1)
|
|
|
{
|
|
|
throw std::out_of_range("Iterator out of range");
|
|
|
}
|
|
|
- return &m_ptr->m_queue[m_index];
|
|
|
+ return &m_ptr->m_queue[m_index];
|
|
|
}
|
|
|
|
|
|
- Iterator& operator++()
|
|
|
- {
|
|
|
+ Iterator& operator++() {
|
|
|
m_index = (m_index + 1) % m_ptr->m_capacity;
|
|
|
if(m_index == m_ptr->m_rear)
|
|
|
{
|
|
|
@@ -141,17 +140,52 @@ public:
|
|
|
}
|
|
|
return *this;
|
|
|
}
|
|
|
+ Iterator operator++(int) {
|
|
|
+ Iterator tmp = *this; // 先保存旧值
|
|
|
+ ++(*this); // 复用前置 ++
|
|
|
+ return tmp; // 返回修改前的迭代器副本
|
|
|
+ }
|
|
|
+ /* 自减比较复杂,迭代器使用 -1 表示 end(),如果 end() 自减,则需要判断是空还是满
|
|
|
+ */
|
|
|
+ Iterator& operator--() {
|
|
|
+ /* 等于 -1 说明是结尾,判断是空还是满 */
|
|
|
+ if(m_index == -1)
|
|
|
+ {
|
|
|
+ if(m_ptr->isEmpty())
|
|
|
+ {
|
|
|
+ /* 是空,返回自身 */
|
|
|
+ return *this;
|
|
|
+ }
|
|
|
+ else if(m_ptr->isFull())
|
|
|
+ {
|
|
|
+ m_index = (m_ptr->m_rear - 1 + m_ptr->m_capacity) % m_ptr->m_capacity;
|
|
|
+ }
|
|
|
+ }else
|
|
|
+ {
|
|
|
+ if(m_ptr->m_front == m_index)
|
|
|
+ {
|
|
|
+ m_index = -1; // 到达开头前面
|
|
|
+ } else
|
|
|
+ {
|
|
|
+ m_index = (m_index - 1 + m_ptr->m_capacity) % m_ptr->m_capacity;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return *this;
|
|
|
+ }
|
|
|
+ Iterator operator--(int) {
|
|
|
+ Iterator tmp = *this; // 先保存旧值
|
|
|
+ --(*this); // 复用前置 --
|
|
|
+ return tmp; // 返回修改前的迭代器副本
|
|
|
+ }
|
|
|
|
|
|
- bool operator!=(const Iterator& other) const
|
|
|
- {
|
|
|
+ bool operator!=(const Iterator& other) const {
|
|
|
if(m_ptr != other.m_ptr)
|
|
|
return true;
|
|
|
if(m_index == other.m_index)
|
|
|
return false;
|
|
|
return true;
|
|
|
}
|
|
|
- bool operator==(const Iterator& other) const
|
|
|
- {
|
|
|
+ bool operator==(const Iterator& other) const {
|
|
|
if(m_ptr != other.m_ptr)
|
|
|
return false;
|
|
|
if(m_index != other.m_index)
|
|
|
@@ -164,7 +198,7 @@ public:
|
|
|
long m_index = -1;
|
|
|
};
|
|
|
|
|
|
- Iterator begin() { return Iterator(this); }
|
|
|
+ Iterator begin() { return Iterator(this, m_front); }
|
|
|
Iterator end() { return Iterator(this, -1); }
|
|
|
};
|
|
|
|