C++Template之Priority_queue

今天学生问了一个程序,涉及到C++模板的使用,在Dev C++中一切编译正常,但是在VC++ 6.0中提示出错。

template
void printQueue(T& priority_queue)
{
    while (!priority_queue.empty())
    {
        cout << priority_queue.top() << " " ;
        priority_queue.pop();
    }
}

int main()
{
    priority_queue priority_queue1;
    priority_queue > priority_queue2;

    for (int i = 0; i < 8; i++)
    {
        priority_queue1.push(i);
        priority_queue2.push(i);
    }

    cout<<"Contents in priority_queue1: ";
    printQueue(priority_queue1);

    cout<< "/nContents in priority_queue2: ";
    printQueue(priority_queue2);

    return 0;
}

priority_queue是STL中所谓的constainer adapter,不是一个真正的容器。

下面是其使用的一个正确示例:

typedef std::priority_queue int_priority_queue;  

template < typename T >  
T const * q_begin ( std::priority_queue const & q ) {  
return ( &( q.top() ) );  
}  

template < typename T >  
T const * q_end ( std::priority_queue const & q ) {  
return ( &( q.top() ) + q.size() );  
}  

int main ( void ) {  
    int_priority_queue q;  
    q.push( 1 );  
    q.push( 2 );  
    q.push( 3 );  
    std::copy(q_begin( q ), q_end( q ), std::ostream_iterator ( std::cout, " " ) );  
    std::cout << '/n';  

 

最后,虽然解决了问题,但是还是无法解释!可以在VC++ 6.0下编译通过!

#include "stdafx.h"
#include "assert.h"
#include "stdlib.h"
#include
#include
#include
using namespace std;


template
void printQueue(priority_queue &s)
{
    while (!s.empty())
    {
        cout << s.top() << " " ;
        s.pop();
    }
}

template
void printQueue2(priority_queue > &s)
{
    while (!s.empty())
    {
        cout << s.top() << " " ;
        s.pop();
    }
}

int main()
{
    priority_queue priority_queue1;
    priority_queue > priority_queue2;

    for (int i = 0; i < 8; i++)
    {
        priority_queue1.push(i);
        priority_queue2.push(i);
    }

    cout<<"Contents in priority_queue1: ";
    printQueue(priority_queue1);

    cout<< "/nContents in priority_queue2: ";
    printQueue2(priority_queue2);

    return 0;
}

参考资料:

http://www.cppblog.com/shyli/archive/2007/04/06/21366.html

你可能感兴趣的:(C++Template之Priority_queue)