列表大小为 1,但 front() 和 back() 不相等
list size is 1 but front() and back() are unequal
导致代码的"错误":
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 向量。
相关文章:
- 两个字符串在 c++ 中不相等
- 如何以优化的方式同时迭代两个间距不相等的数组
- 是否确保 2 个连续的 std::chrono::steady_clock::now() 不相等?
- C ++相同的字符串不相等(实际上是char*)
- 在 c++ 中比较不相等数组或字符串的方法
- C++ - 空的 std::list begin() 和 end() 不相等
- 列表大小为 1,但 front() 和 back() 不相等
- C++中[不]相等运算符的求值顺序
- 2 个指针,0 字节相差但不相等
- 将不相等的线读入向量的向量
- 如何打印一个不相等的三角形
- 为什么这两个char阵列不相等
- 不(!)和不相等(!=)之间有什么区别是C
- 为什么这些C 元组不相等
- 为什么整数的地板本身不相等(CPP)
- 当使用不相等vs均等时,是否存在任何性能差异
- 为什么这两个值在 arduino 上不相等
- 字符串在相等时比较不相等
- 将字符转换为 int 会显示不相等的数字
- glXCreateWindow在VISUAL_ID和屏幕>root_visual不相等时不起作用