在这里,我写了一个简单队列类模板:C++:STD的顺序::法院
#include "stdafx.h"
#include "iostream"
#include "conio.h"
template <class T> class Queue {
private:
struct Node {
T value;
Node *next;
};
Node *first, *last;
public:
Queue() { //Initialization
first = 0;
last = 0;
};
void push(T value) { //Put new value into Queue
Node *p = new Node;
p->value = value;
if (!first) //If Queue is not empty
first = p;
else
last->next = p;
last = p; //Put the value to the last of the Queue
};
T get() { //Get the first value of the Queue
return (first) ? first->value : NULL;
};
T pop() { //Take the first value out of Queue
T result = first->value;
Node *temp = first;
first = first->next;
delete temp;
return result;
};
};
int _tmain(int argc, _TCHAR* argv[])
{
Queue<int> bag;
bag.push(1); //Bag has value 1
bag.push(2); //Bag has values: 1, 2
std::cout << bag.get() << '\n' << bag.pop() << '\n' << bag.pop();
_getch();
return 0;
}
有一个问题 - 输出为:
0
2
1
/*
Correct output should be:
1
1
2
*/
当调试的std::cout
行,我发现程序调用bag.pop()
在最右边的第一个,然后bag.pop()
,最后bag.get()
。 这是正确的顺序吗?
的顺序是不确定的,如果你需要一个特定的顺序您的cout语句分成三段。 'std :: cout << bag.get()<<'\ n'; std :: cout << bag.pop()<<'\ n'; std :: cout << bag.pop();' – john
如果你搜索了,你会发现一些答案:[cout <<打印函数的调用顺序?](http://stackoverflow.com/questions/2129230/ cout-order-of-call-to-functions-it-prints/2129242#2129242)&[使用std :: cout评估参数的顺序](http://stackoverflow.com/questions/7718508/order-of-评估的参数使用stdcout) – crashmstr
如果模板类型'T'不是一个指针?那么你不能在'get'函数中返回'NULL'(除非'T'是一个可以从整数'0'隐式创建的类型)。 –