如何在 C++ 中使用 map 存储 bi-directional 图?

How to store a bi-directional graph using map in C++?

我正在尝试使用 std::map<int,vector<int>> 将 bi-directional 图存储为邻接表。这里的想法是存储n个节点,从1到n在这个映射中。 输入为 u v,表示节点 u 和节点 v 之间的边。我们在 n 行上得到 n 个这样的输入。 我存储图表的代码:

    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);
    }

这应该可行,但在符合 C++ 14 时它给了我错误。然后我用 C++ 17 编译了它,但错误仍然存​​在。 错误(显示在我的终端上):

/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]

我觉得我用来存储图形的脚本是正确的,因为我的朋友能够 运行 此代码在他的系统上完全正常。我不知道为什么会报错。

我的系统:debian 10

Headers 使用:#include<bits/stdc++.h>

关于我的编译器的一些信息:

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$ 

你的错误是你试图让一个名为 graph() 的函数删除括号然后一切都会好起来的。