C++:basic_string::_M_construct 空,对于图形 BFS 算法无效错误
C++: basic_string::_M_construct null not valid error for Graph BFS algorithm
这是使用模板的图形的标准BFS算法。该算法适用于除字符串之外的所有基本数据类型。我知道这是当空值传递给 std::string(( 时引起的,但我无法确切地弄清楚为什么代码中首先应该有一个空字符串。
#include <bits/stdc++.h>
using namespace std;
template < typename T >
class Graph {
unordered_map < T, list < T >> adjList;
public:
void addEdge(T u, T v, bool birdir = true) {
adjList[u].push_back(v);
if (birdir)
adjList[v].push_back(u);
}
void printG() {
for (auto i: adjList) {
cout << i.first << "->";
for (auto nodes: i.second) {
cout << nodes << ",";
}
cout << endl;
}
}
void BFS(T src) {
queue < T > Q;
unordered_map < T, bool > visited;
Q.push(src);
//Q.push(nullptr);
visited[src] = true;
while (!Q.empty()) {
T f = Q.front();
Q.pop();
cout << f << " -- ";
for (auto neighbor: adjList[f]) {
if (!visited[neighbor]) {
visited[neighbor] = true;
Q.push(neighbor);
}
}
}
}
};
int main() {
Graph < string > * g = new Graph < string > ();
g - > addEdge("0", "1", false);
g - > addEdge("1", "3");
//g->printG();
cout << endl;
g - > BFS(0);
}
这里的问题是你如何称呼BFS
。 你使用
g - > BFS(0);
它试图从0
构建一个std::string
. 0
是空指针常量,由于std::string
具有需要const char*
的重载,因此编译器调用该构造函数。 但是,这样做是无效的,因为指针不能是空指针。 这会导致您遇到异常。 您需要将代码更改为
g - > BFS("");
甚至更简单
g - > BFS();
Graph<std::string>::BFS
是一个接受std::string
的成员函数。调用 g->BFS(0);
时,0
用于构造 std::string
参数,并调用采用const char*
的构造函数。这称为std::string::string(nullptr)
.
若要避免0
在 gcc 中的代码中被解释为空指针,请使用 -Wzero-as-null-pointer-constant
。你可能的意思是g->BFS("0")
(字符串"0"
(
相关文章:
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- C++图形类指针混淆
- 我的代码中有错误吗?使用BGI图形的C++代码对我不起作用
- 如何在内核C++中使用1920x1080x16M图形或类似的16M颜色?(VGA)
- 如何用C++编写BFS函数
- 这是实现图形的坏方法吗
- 打印 ONNXRUNTIME::图形没有模型
- 使用 bfs 解决连接组件问题时得到错误的答案
- 提升如何在图形可视化中写入边缘的权重?
- C++:basic_string::_M_construct 空,对于图形 BFS 算法无效错误
- 使用 BFS(无向)克隆图形
- BFS 用于使用链接列表、C++ 的图形
- 提升图形库:顶点过滤图上的 BFS
- BFS可以在图形中找到周期吗?
- 邻接列表,用于创建图形和广度优先搜索 (BFS) 和 Fepth First Search (DFS)
- BFS 和 DFS 的图形在C++
- 运行 BFS 以查找从图形底部到顶部的最短路径
- 如何避免在BFS中进一步搜索顶点的邻居?我正在使用提升图形库
- 在Boost图形库中进行BFS时如何修改属性
- 检查图形是否使用 BFS 连接并打印 MST