Reputation: 236
I am trying to define an undirected weighted graph with vertexes as a string but having trouble with adding edges. I tried this method with normal map<string, vector<int>>
and it works fine but with map<string, vector<structure>>
it doesn't work.
Here's my approach:
#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);
}
Error that I got:
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);
^
What am I doing wrong?
Upvotes: 0
Views: 51
Reputation: 6326
I think you have a mixed array with hashmaps, in your case std::unordered_map
is enough. We don't need to use array of std::unordered_map
or std::vector<std::unordered_map<std::string, AdjListNode>>
.
Then the fixed code:
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);
}
Upvotes: 1