[英]How to store a bi-directional graph using map in C++?
I am trying to store a bi-directional graph as an adjacency list using std::map<int,vector<int>>
.我正在尝试使用
std::map<int,vector<int>>
将双向图存储为邻接列表。 The idea here is to store n nodes, from 1 to n in this map.这里的想法是在这个 map 中存储 n 个节点,从 1 到 n。 The input is given as
uv
, which denotes an edge between node u and node v. We get n such inputs on n lines.输入为
uv
,表示节点 u 和节点 v 之间的一条边。我们在 n 行上得到 n 个这样的输入。 My code for storing the graph:我用于存储图形的代码:
int u,v;
map<int,vector<int>> graph();
for(int i=0;i<n;i++) {
cin >> u >> v;
graph[u].push_back(v);
graph[v].push_back(u);
}
This should work, but it gave me errors when complied with C++ 14. I then compiled this with C++ 17 and the errors still persists.这应该可以,但是在遵守 C++ 14 时它给了我错误。然后我用 C++ 17 编译了它,错误仍然存在。 Errors(as displayed on my terminal):
错误(显示在我的终端上):
/home/chirag/chiragC/forces/try.cpp: In function ‘void solve()’:
/home/chirag/chiragC/forces/try.cpp:68:10: warning: pointer to a function used in arithmetic [-Wpointer-arith]
graph[u].push_back(v);
^
/home/chirag/chiragC/forces/try.cpp:68:12: error: request for member ‘push_back’ in ‘*(graph + ((sizetype)u))’, which is of non-class type ‘std::map<int, std::vector<int> >()’
graph[u].push_back(v);
^~~~~~~~~
/home/chirag/chiragC/forces/try.cpp:69:10: warning: pointer to a function used in arithmetic [-Wpointer-arith]
graph[v].push_back(u);
^
/home/chirag/chiragC/forces/try.cpp:69:12: error: request for member ‘push_back’ in ‘*(graph + ((sizetype)v))’, which is of non-class type ‘std::map<int, std::vector<int> >()’
graph[v].push_back(u);
^~~~~~~~~
[Finished in 1.5s with exit code 1]
I feel the script I am using to store the graph is correct, as my friend was able to run this code completely fine on his system.我觉得我用来存储图表的脚本是正确的,因为我的朋友能够在他的系统上完全运行这段代码。 I don't know why it is giving errors.
我不知道为什么它会给出错误。
My System: debian 10我的系统:debian 10
Headers used: #include<bits/stdc++.h>
使用的标头:
#include<bits/stdc++.h>
Some info on my Compiler:关于我的编译器的一些信息:
chirag@debian10:~/chiragC/forces$ ls /usr/bin | grep g++
arm-none-eabi-g++
avr-g++
g++
g++-8
x86_64-linux-gnu-g++
x86_64-linux-gnu-g++-8
chirag@debian10:~/chiragC/forces$ g++ --version
g++ (Debian 8.3.0-6) 8.3.0
Copyright (C) 2018 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
chirag@debian10:~/chiragC/forces$
Your bug is that you are trying to make a function named graph()
remove the parenthesis then all will be fine.您的错误是您正在尝试制作名为
graph()
的 function 删除括号,然后一切都会好起来的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.