2013-11-21 59 views
1

在这里,我写了一个简单队列类模板: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()。 这是正确的顺序吗?

+5

的顺序是不确定的,如果你需要一个特定的顺序您的cout语句分成三段。 'std :: cout << bag.get()<<'\ n'; std :: cout << bag.pop()<<'\ n'; std :: cout << bag.pop();' – john

+0

如果你搜索了,你会发现一些答案:[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

+1

如果模板类型'T'不是一个指针?那么你不能在'get'函数中返回'NULL'(除非'T'是一个可以从整数'0'隐式创建的类型)。 –

回答

4
T get() { //Get the first value of the Queue 
    return (!first) ? first->value : NULL; 
}; 

这倒退了。丢掉!。你是在说:“如果first非空,(即如果first空),使用它。

也就是说,一个参数评测给函数的顺序是不确定的(编译器可以计算。按任意顺序感觉,只要他们都做本身的功能开始之前)也就是说get()pop()pop()可以以任何顺序被称为参数来调用它们单独的语句:

int a = bag.get(); 
int b = bag.pop(); 
int c = bag.pop(); 
std::cout << a << b << c; 
+0

谢谢。我修复了这个错误,但程序抛出了异常,因为在程序调用另外两个'bag.pop()'后,first-> value没有任何值返回。 –

0
T get() { //Get the first value of the Queue 
    return (!first) ? first->value : NULL; 
}; 

如果first有效,则返回NULL。这被解释为零。你应该颠倒你的逻辑。

+0

谢谢。我修正了这个问题。 –

0

是的,在计算参数的函数时没有指定。通过这个简单的测试,你会得到那是什么意思。

#include <iostream> 
int b(void) {std::cout<<3<<std::endl; return 3;} 
int c(void) {std::cout<<4<<std::endl; return 4;} 
int main(int argc, char *argv[]) 
{ 
    int d = b() + c(); 
    std::cout<<d<<std::endl; 
    return 0; 
} 

所以你会得到3 4 5或4 3 5