【问题标题】:error in map with custom data structure as value使用自定义数据结构作为值的地图错误
【发布时间】:2021-10-05 17:25:47
【问题描述】:

我正在尝试定义一个以顶点为字符串的无向加权图,但在添加边时遇到了麻烦。我用普通的map<string, vector<int>>尝试了这个方法,它工作正常,但map<string, vector<structure>>它不起作用。

这是我的方法:

#include <bits/stdc++.h>
using namespace std;

class AdjListNode
{
    string v;
    int weight;
    public:
        AdjListNode(string _v, int _w){v = _v; weight = _w;}
        string getV(){return v;}
        int getWeight(){return weight;}
};

class Graph
{
    int V;
    map<string, vector<AdjListNode>> *mp;
    public:
        Graph(int V);
        void addedge(string u, string v, int weight);
};

Graph::Graph(int V)
{
    this->V = V;
    mp = new map<string, vector<AdjListNode>>[V];
}

void Graph::addedge(string u,string v,int weight)
{
    AdjListNode node1(v,weight);
    mp[u].push_back(node1);                //<-error here
    AdjListNode node2(u,weight);
    mp[v].push_back(node2);             
}

int main()
{
    int v = 9;
    Graph g(v);
    g.addedge("A","B",4);
    g.addedge("A","C",8);
    g.addedge("B","C",11);
    g.addedge("B","D",8);
    g.addedge("C","E",7);
    g.addedge("C","F",1);
    g.addedge("D","E",2);
    g.addedge("E","F",6);
    g.addedge("D","G",7);
    g.addedge("D","H",4);
    g.addedge("F","H",2);
    g.addedge("G","H",14);
    g.addedge("G","I",9);
    g.addedge("H","I",10);
}

我得到的错误:

In member function 'void Graph::addedge(std::cxx11::string, std::cxx11::string, int)':
D:\c++\graph\custom_vertex_undirected_weighted.cpp:33:7: error: no match for 'operator[]' (operand types are 'std::map<std::cxx11::basic_string, std::vector >*' and 'std::cxx11::string {aka std::cxx11::basic_string}')
mp[u].push_back(node1);
^

我做错了什么?

【问题讨论】:

  • mp 不是map,而是一个指针。
  • mp 是指针,改为写(*mp)[u].push_back
  • new map&lt;string, vector&lt;AdjListNode&gt;&gt;[V] 太糟糕了。避免所有那些教授这一点的垃圾编码网站。
  • 为什么mp是指针?将其更改为成员变量,您不必创建或删除它等。
  • 至少std::vector&lt;std::map&lt;...&gt;&gt;。这也有点糟糕(标准容器的深度嵌套是一个危险信号),但至少你不会有内存泄漏。

标签: c++ algorithm data-structures graph


【解决方案1】:

我认为您有一个带有哈希图的混合数组,在您的情况下 std::unordered_map 就足够了。我们不需要使用std::unordered_mapstd::vector&lt;std::unordered_map&lt;std::string, AdjListNode&gt;&gt; 的数组。

然后是固定代码:

class Graph {
  int V;
  map<string, vector<AdjListNode>> mp;

 public:
  Graph(int V);
  void addedge(string u, string v, int weight);
};

Graph::Graph(int V) { this->V = V; }

void Graph::addedge(string u, string v, int weight) {
  AdjListNode node1(v, weight);
  mp[u].push_back(node1);
  AdjListNode node2(u, weight);
  mp[v].push_back(node2);
}

Online demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    • 2021-04-07
    • 2017-07-22
    • 2020-11-08
    • 2011-12-17
    相关资源
    最近更新 更多