列表的邻接列表错误

adjacency list error with list

基本上我生成了一个 adj_matrix 并且我想从 adj_matrix 生成一个 adj_list...但是我一直收到一条错误消息说 "no match for call..." 我在没有 aPair 的情况下尝试过,我仍然遇到同样的错误,我似乎无法弄清楚我的问题是什么。谁能告诉我为什么列表不起作用?列表在代码的最后

int **gen_random_graph(int n)
{
    srand(time(0));
    int **adj_matrix = new int*[n];
     for(int i = 0; i < n; i++)
     {
        for (int j = i; j < n; j++)   //generating a N x N matrix  based on the # of vertex input
        {
            adj_matrix[i] = new int[n];
        }
     }

    for(int u = 0; u < n; u++)
    {
        for (int v = u; v < n; v++)
        {
            bool edgeOrNot = rand() % 2;   //decide whether it has an edge or not
            adj_matrix[u][v] = adj_matrix[v][u] = edgeOrNot;
            if(adj_matrix[u][v] == true)
            {
                adj_matrix[v][u] = true;
                if(u == v)                            //We can't have i = j in an undirected graph so we set it to false
                {
                    adj_matrix[u][v] = -1;
                }
            }
            else                                        //if adj_matrix[u][v] is false set the symmetry to be false
            {
                adj_matrix[v][u] = adj_matrix[u][v] = -1;
            }
        }

    }
    for(int i = 0; i < n; i++)
    {
        for(int j = i; j < n; j++)           //create the N x N with edges and sets the weight between the edge randomly
        {
            if(adj_matrix[i][j] == true)
            {
                    int weight = rand() % 10 + 1;
                    adj_matrix[i][j] = adj_matrix[j][i] = weight;
                    cout << " ( " << i << "," << j << " ) " << "weight: " << adj_matrix[i][j] << endl;
            }
        }
    }



 for(int i = 0; i < n; i++)
{
    vector<int> adj_list;
    for(int j = i; j < n; j++)
    {
        if(adj_matrix[i][j] > 0)
        {
           int weight = adj_matrix[i][j];
           adj_list.push_back(j);
           cout << adj_list[i] <<  " " << endl;
        }
    }
}
    print(n,adj_matrix);
    return (adj_matrix);
}

我看到 adj_list 不可调用,因此您的代码已损坏。有几个简单的解决方案。在 these docs, you may simply either access listObj.front() and listObj.back() OR you may also just create an iterator using listObj.begin() and iterating over the two elements (which may be desirable if you ever decide to put more than two elements in the list). See this tutorial 摘要上方的代码片段中查看有关为列表创建迭代器的简单示例。

请注意,在这里,我为 simplicity/abstraction 调用的列表对象 listObj 将只是底部循环中的 adj_matrix[i][j]。那应该可以解决您的语法错误。

此外,除了您的代码语法之外,我不明白您为什么要尝试将权重推入列表,然后打印出来并返回邻接矩阵。我也不明白为什么当您似乎只想将整数权重推到它上面时您会使用成对对象列表。为此,您可以使用一个简单的整数向量(即:vector <int> adj_list;)...或者更简单,您可以使用一个简单的整数数组...而不是使用成对列表的向量。

编辑:在 运行 本地代码并查看值后,我意识到问题是 OP 输出中的错误只是他在 C++ 中使用 "true" 代替一个整数,它正在创建一个错误,如 this SO post. The OP also has a further design decision to make where adjacency lists are concerned. More on what an adjacency list is, conceptually, found on Wikipedia.

中所述