显示和添加邻接表图形的方法 [英] Display and add methods for adjacency list graph
问题描述
这是我第三次使用c ++中的邻接表创建图形.使用OOP很重要.我觉得这个问题的答案确实很简单,但是我无法修复和改进我的代码.
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.
有:
#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;
}
所以现在在Visual Studio中,我出现了一个错误:
So now in Visual Studio I have an error:
'std :: vector> :: vector(const std :: vector< _Ty,std :: allocator< _Ty >>&)):无法将参数1从'std :: vector>'转换为'const _Alloc &'
'std::vector>::vector(const std::vector<_Ty,std::allocator<_Ty>> &)': cannot convert argument 1 from 'std::vector>' to 'const _Alloc &'
此外,在display()方法中存在有符号/无符号不匹配.我不知道我的方法是否有问题,但是我被困在这里.
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.
推荐答案
vector<vector<int>> baseVec;
接受vector<int>
s
vector<Edge> subVec;
baseVec.emplace_back(subVec);
尝试喂它vector<Edge>
s.这没有道理.
Attempts to feed it vector<Edge>
s. This does not make sense.
vector<vector<Edge>> baseVec;
感觉更好.
请注意,
cout << baseVec[i][j];
尝试打印edge
,但不知道如何. 进行operator<<
重载以处理edge
或更改您的输出.
tries to print an edge
and does not know how. Either make an operator<<
overload to handle edge
or change what you're outputting.
这篇关于显示和添加邻接表图形的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!