2011-04-13 47 views
0

我无法将pair<int, int>类型的对象插入到队列中。我收到一个奇怪的错误,我不知道如何去解决它。谁能帮忙?以下是该方法的代码,然后是错误消息。前两个错误是为插入,最后是为operator=的使用,帮助与此也将不胜感激。谢谢!如何将队列<int, int>插入队列?

pair<int,int>* bfSpanningTree(int theVertex) 
{ 
    queue< pair<int,int> > pairq; 
    queue<int> nodeq; 
    if(linkedAdjacencyList[theVertex]->value == theVertex && linkedAdjacencyList[theVertex]->adj != NULL) 
    { 
     Node* whereto; 
     whereto = linkedAdjacencyList[theVertex]->adj; 
     while(whereto->adj != NULL) 
     { 
      pairq.push(pair< &whereto->value, &whereto->adj->value >); 
      nodeq.push(whereto->value); 
      whereto = whereto->adj; 
     } 
     while(!nodeq.empty()) 
     { 
      whereto = linkedAdjacencyList[theVertex]->adj; 
      while(whereto->adj != NULL) 
      { 
       pairq.push(pair<&whereto->value, &whereto->adj->value>); 
       whereto = whereto->adj; 
      } 
     } 
    } 
    int i = 0; 
    pair<int,int>* retVal; 
    pair<int,int> tree[pairq.size()]; 
    while(!pairq.empty()) 
    { 
     tree[i] = pairq.pop(); 
     i++; 
    } 
    retVal = tree; 
    return retVal; 
} 

~UndirectedGraph() 
{ 
    for (int i = 0; i < numVerticies; i++) 
     delete[] linkedAdjacencyList[i]; 
} 

错误:

的代码

hw8.h:181: error: wrong number of template arguments (1, should be 2)

/usr/include/c++/4.4/bits/stl_pair.h:67: error: provided for ‘template<class _T1, class _T2> struct std::pair’

hw8.h:190: error: wrong number of template arguments (1, should be 2)

/usr/include/c++/4.4/bits/stl_pair.h:67: error: provided for ‘template<class _T1, class _T2> struct std::pair’

hw8.h:200: error: no match for ‘operator=’ in ‘tree[i] = pairq.std::queue<_Tp, _Sequence>::pop [with _Tp = std::pair<int, int>, _Sequence = std::deque<std::pair<int, int>, std::allocator<std::pair<int, int> > >]()’

/usr/include/c++/4.4/bits/stl_pair.h:68: note: candidates are: std::pair<int, int>& std::pair<int, int>::operator=(const std::pair<int, int>&)

+0

哪行代码在'hw8.h'行181? – 2011-04-13 02:11:38

回答

7

行,像这样:

pairq.push(pair< &whereto->value, &whereto->adj->value >); 

或许应该是这样的:

pairq.push(make_pair(whereto->value, whereto->adj->value)); 

,或者如果value成员不是的键入int

pairq.push(pair<int,int>(whereto->value, whereto->adj->value)); 

最后,queue::pop()不返回任何东西,所以你可能想:

tree[i] = pairq.front(); 
pairq.pop(); 
1

您不能从实际的对象实例化模板像你这样做......他们必须是由模板函数被实例化的对象类型(在这种情况下,构造)。

因此,举例来说,你可以使用构造就像让一对对象:

pair<int, int>(whereto->value, whereto->adj->value)

或者,您可以用如图迈克尔效用函数make_pair()一对。

但如果你打算使用构造函数,你必须从某个地方声明,将取代类型T1T2在构造函数的声明,即类型,

template<typename T1, typename T2> 
pair::pair(const T1& object_1, const T2& object_2); 

即通过声明进行对象与所需对象类型的模板参数(即,对于一对int对象,您将使用pair<int, int>),然后用这些类型的对象调用实际对象成员函数(在您的情况下,它将是类的构造函数pair)。

0

乍一看这里有几件事 - 你能提供Node类/结构定义吗?

  • 您正在返回一个指向自动(堆栈)元素的指针,它将超出范围。您将希望按值返回,很可能(或者,分配并返回一个指针,最好是共享的元素)
  • 队列。pop()返回void - 参见http://www.cplusplus.com/reference/stl/queue/pop/