问题
This is my third time for creating a graph using adjacency list in c++. It's important to use OOP. I feel like the answer to this problem is really simple, but I can't manage to fix and improve my code.
There is it:
#include <iostream>
#include <algorithm>
#include <fstream>
#include <vector>
using namespace std;
struct Edge
{
int begin;
int end;
};
class Graph
{
private:
int numOfNodes;
vector<vector<int>> baseVec;
public:
Graph(int numOfNodes)
{
//baseVec->resize(numOfNodes, vector<int>(numOfNodes));
for (int i = 0; i < numOfNodes; i++)
{
vector<Edge> subVec;
baseVec.emplace_back(subVec);
}
}
void newEdge(Edge edge)
{
if (edge.begin >= numOfNodes && edge.end >= numOfNodes)
{
cout << "Invalid edge!\n";
}
baseVec[edge.begin].emplace_back(edge.end);
baseVec[edge.end].emplace_back(edge.begin);
}
void display()
{
cout << baseVec.size();
for (int i = 0; i < baseVec.size(); i++)
{
cout << "\n Adjacency list of vertex " << i << "\n head ";
for (int j = 0; j < baseVec[i].size(); j++)
{
cout << baseVec[i][j];
cout << endl;
}
}
}
};
int main()
{
int vertex, numberOfEdges, begin, end;
cout << "Enter number of nodes: ";
cin >> vertex;
numberOfEdges = vertex * (vertex - 1);
Edge edge;
Graph g1(vertex);
for (int i = 0; i < numberOfEdges; i++)
{
cout << "Enter edge ex.1 2 (-1 -1 to exit): \n";
cin >> edge.begin >> edge.end;
if ((begin == -1) && (end == -1))
{
break;
}
g1.newEdge(edge);
}
g1.display();
return 0;
}
So now in Visual Studio I have an error:
'std::vector>::vector(const std::vector<_Ty,std::allocator<_Ty>> &)': cannot convert argument 1 from 'std::vector>' to 'const _Alloc &'
Also that in display() method there is signed/unsigned mismatch. I don't know If there is something wrong with my methods but I'm stuck here.
回答1:
vector<vector<int>> baseVec;
accepts vector<int>
s
vector<Edge> subVec;
baseVec.emplace_back(subVec);
Attempts to feed it vector<Edge>
s. This does not make sense.
vector<vector<Edge>> baseVec;
Makes better sense.
Note that this change will set up another blast of errors when
cout << baseVec[i][j];
tries to print an edge
and does not know how. Either make an operator<< overload to handle edge or change what you're outputting.
来源:https://stackoverflow.com/questions/53326934/display-and-add-methods-for-adjacency-list-graph