C++ 列表大小为1,但front()和back()不相等
导致错误的代码:C++ 列表大小为1,但front()和back()不相等,c++,list,stl,C++,List,Stl,导致错误的代码: 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
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;
}
我的意见是:
109
2 1
3 1
4 3
5 2
6 1
7 2
8 6
9 8
108
我得到的输出:
正面==8
返回==1
2 1
我的尺码是1码
分段故障堆芯
现在,如果列表的大小是1,那么前面和后面怎么会不同呢?即使它们不同,当值作为back元素出现在列表中时,为什么remove会给出分段错误
观察:
给出的分段错误早于。
请原谅我糟糕的调试方法,但这一观察结果意味着a cout您将10作为v传递给addEdge,试图访问第11个元素。adj向量有10个元素,因此您在内存中的某个地方写入了不应该写入的内容。
在任何情况下,手动分配和分配是麻烦的配方,考虑使用STL向量。看起来像未定义的行为。你到底为什么在那里使用原始指针?@πάνταῥεῖ - 实际上,我从中复制了Graph类。这就是这个错误的原因吗?对非POD类型使用malloc几乎肯定是错误的。这也表明你不明白自己在做什么。当你使用这些输入添加边时会遇到问题,所以它以后会做的是。。。不太相关。您可能感兴趣的是C++使用基于零的索引。在覆盖计算机内存中的“谁知道”之后,发现其他变量的值错误或类对象处于不稳定状态是很正常的。这是一个冗长的方式说未定义的行为,这是第一个评论。。。只有你显然不明白,所以我给出了长版本。