- 論壇徽章:
- 0
|
template<class T>
class RingQueue {
public:
RingQueue() {
cout << "RingQueue::ctor" << endl;
};
virtual ~RingQueue() {
cout << "RingQueue::destory" << endl;
};
void InitQueue() {
Push_Count = 0;
Push_Index = 0;
Pop_Count = 0;
Pop_Index = 0;
memset(List, 0, sizeof (List));
}
bool Push(const T& AData) {
if (Push_Count - Pop_Count < Max_Count) {
List[Push_Index] = AData;
Push_Count++;
if (Push_Index == High_Index)
Push_Index = 0;
else
Push_Index++;
return true;
} else
return false;
}
T Pop() {
T result = NULL;
if (Push_Count != Pop_Count) {
result = List[Pop_Index];
Pop_Count++;
if (Pop_Index == High_Index)
Pop_Index = 0;
else
Pop_Index++;
}
return result;
}
long size() {
return this->Push_Count - this->Pop_Count;
}
private:
RingQueue(const RingQueue& orig);
T List[524288 * 2]; //2^19 4M�ռ�
const static unsigned long Max_Count = 524288 * 2;
const static unsigned long High_Index = 524288 * 2 - 1;
unsigned long Push_Count;
unsigned long Push_Index;
unsigned long Pop_Count;
unsigned long Pop_Index;
};
---------------------------------------------------------無(wú)奈的分割線
之前的“編譯器亂序優(yōu)化”,我開(kāi)始說(shuō)Pop()函數(shù)里改成if (Push_Count > Pop_Count)可以避免,想到溢出時(shí)的情況就不成立了,改成if (Push_Count - Pop_Count > 0)就好,但Push函數(shù)也會(huì)有類似的問(wèn)題,就是在環(huán)形隊(duì)列滿的時(shí)候,所以我改成如下:
bool Push(const T& AData) {
if (size() < Max_Count) {//環(huán)形隊(duì)列不滿
if(List[Push_Index] != NULL)//這時(shí)候元素還沒(méi)被pop出去
return false;
List[Push_Index] = AData;
Push_Count++;
if (Push_Index == High_Index)
Push_Index = 0;
else
Push_Index++;
return true;
} else
return false;
}
T Pop() {
T result = NULL;
if (size() > 0) {//環(huán)形隊(duì)列不為空
result = List[Pop_Index];
Pop_Count++;
if (Pop_Index == High_Index)
Pop_Index = 0;
else
Pop_Index++;
List[Pop_Index] = NULL;//已經(jīng)pop的元素清空,放到這里防止編譯器跟Pop_Count++;語(yǔ)句優(yōu)化成序列顛倒
}
return result;
}
|
|