列表大小为 1,但 front() 和 back() 不相等

list size is 1 but front() and back() are unequal

本文关键字:back 不相等 front 小为 列表      更新时间:2023-10-16

导致代码的"错误":

struct Edge
{
    int src, dest;
};
// Graph class represents a directed graph using adjacency list representation
class Graph
{
    int V;    // No. of vertices
    list<int> *adj;    // Pointer to an array containing adjacency lists
    void DFSUtil(int v, bool visited[], int &count);  // A function used by DFS
public:
    Graph(int V);   // Constructor
    void addEdge(int v, int w);   // function to add an edge to graph
    void rmEdge(int v, int w);
    int DFS(int v);    // DFS traversal of the vertices reachable from v
};
Graph::Graph(int V)
{
    this->V = V;
    adj = new list<int>[V];
}
void Graph::addEdge(int v, int w)
{
    adj[v].push_back(w); // Add w to v’s list.
}
void Graph::rmEdge(int v, int w)
{
    cout << "front == " << adj[v].front() << endl;
    cout << "back == " << adj[v].back() << endl;
    cout << v << " " << w << endl;
    cout << "My size is " << adj[v].size() << endl; 
    adj[v].remove(w);
}
int main()
{
    int n, m;
    cin >> n >> m;
    struct Edge* edges = new Edge[m];
    Graph g(n);
    for (int i = 0; i < m; ++i)
    {
        int temp1, temp2;
        cin >> temp1 >> temp2;
        g.addEdge(temp1, temp2);
        edges[i].src = temp1;
        edges[i].dest = temp2;
    }
    for (int i = 0; i < m; ++i)
    {
        g.rmEdge(edges[i].src, edges[i].dest);
    }
    return 0;
}

我给出的输入:

10 9 2 1 3 1 4 3 5 2 6 1 7 2 8 6 9 8 10 8

我得到的输出:

前 == 8
返回 == 1
2 1
我的尺码是 1
分段故障(核心转储(

现在,如果列表的大小是 1,那么 front(( 和 back(( 怎么会不同呢?即使它们不同,为什么当值存在于列表中(作为 back(( 元素(时remove()给出分段错误?

观察:

此代码给出Segmentation fault早于此代码。
请原谅我糟糕的调试方法,但这一观察结果暗示cout << endl;导致输出以不应该发生的方式发生变化。这里发生了什么,我无法理解它?

编辑:我将malloc更改为new,但仍然保持相同的行为。

您将"10"作为"v"传递给addEdge,尝试访问第11个元素。adj 向量有 10 个元素,因此你在内存中不应该写的某个地方。在任何情况下,手动分配和取消分配都是麻烦,请考虑使用 stl 向量。