如何将pair<int, int>插入队列?

3

我在向队列中插入pair<int, int>类型的对象时遇到了问题。我得到了一个奇怪的错误,不知道如何解决。有人能帮忙吗?下面是该方法的代码,后跟错误消息。前两个错误是为了插入,最后一个是关于使用operator=,也需要帮助。谢谢!

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: 错误:模板参数数量错误(应为2,实际为1)

/usr/include/c++/4.4/bits/stl_pair.h:67: 错误:提供了‘template<class _T1, class _T2> struct std::pair’

hw8.h:190: 错误:模板参数数量错误(应为2,实际为1)

/usr/include/c++/4.4/bits/stl_pair.h:67: 错误:提供了‘template<class _T1, class _T2> struct std::pair’

hw8.h:200: 错误:没有与‘operator=’匹配的函数‘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: 注意:候选函数是:std::pair<int, int>& std::pair<int, int>::operator=(const std::pair<int, int>&)


hw8.h文件的第181行是哪一行代码? - Matt Ball
4个回答

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

看一下make_pair()queue::pop()不会返回第一个元素。你需要以下内容:

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

1

你不能像你所做的那样从实际对象实例中创建模板...它们必须是由模板函数(在这种情况下是构造函数)实例化的对象的类型。

例如,您可以使用类似以下构造函数来创建一对对象:

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

或者您可以使用实用程序函数make_pair()来创建一对对象,就像Michael所展示的那样。

但是,如果您要使用构造函数,则必须在某个地方声明将替换构造函数声明中的类型T1T2的类型。

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

这是通过使用所需对象类型的模板参数来声明对象来完成的(例如,对于一对int对象,您将使用pair<int, int>),然后使用那些类型的对象调用实际的对象成员函数(在您的情况下,应该是pair类的构造函数)。

0

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接