c++ - 在 C++ 中创建字符串的邻接列表
问题描述
我想使用字符串在我的邻接列表中添加一条边。以下是我到目前为止所拥有的。我从 file(void connections(string file)) 读取数据,我想在列表中添加一条边。我的文件都已加载,我得到了所有数据,但边缘是问题所在。我们要实现自己的图形数据结构,而不是使用任何库,如列表或地图我的 display_AdjList(Node* h) 方法也很难用字符串实现。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct Populace{
string p_name;
int p_age;
float p_spread_prob;
float p_d_prob;
};
struct Node {
string val;
Node* next;
};
struct graphEdge {
string start_ver, end_ver;
};
string name;
int age;
float prob;
class Graph{
private:
Node* getNode(string p, Node* head){
Node* newNode = new Node;
newNode->val = p;
newNode->next = head;
return newNode;
}
int N;
graphEdge edge[];
Populace *person;
public:
Node **head;
Graph(int N) {
head = new Node*[N]();
this->N = N;
person=new Populace[N];
}
void read_from_file(string file){
ifstream fil;
string info;
int i;
fil.open(file.c_str());
while (fil>>name>>age>>prob)
{
getline(fil,info);
person[i].p_name=name;
person[i].p_age=age;
person[i].p_spread_prob=prob;
i++;
}
}
int index(string h){
for(int i=0;i<N;i++){
if(h==person[i].p_name){
return i;
}
}
}
void con_add(string start, string end){
int star=index(start);
for (int i = 0; i < N; ++i){
head[i] = nullptr;
for(int j=0;j<N;j++){
start=edge[i].start_ver;
end= edge[i].end_ver;
Node* newnode=getNode(end,head[star]);
head[star]=newnode;
}
}
}
void connections(string file){
ifstream fil;
string info;
int i;
string start_ver,end_ver;
fil.open(file.c_str());
while (fil>>start_ver>>end_ver){
getline(fil,info);
cout<<start_ver<<","<<end_ver;
cout<<endl;
con_add(start_ver,end_ver);
}
}
void print_population(){
for(int i=0;i<N;i++){
cout<<person[i].p_name<<" ";
cout<<person[i].p_age<<" ";
cout<<person[i].p_spread_prob<<endl;
}
}
~Graph() {
for (int i = 0; i < N; i++)
delete[] head[i];
delete[] head;
}
void display_AdjList(Node* h)
{
string m;
for(int i=0;i<N;i++){
m=person[i].p_name;
while (h != nullptr) {
cout << "(" << m << ", " << h ->val
<< ", " << ") ";
h = h->next;
}
}
cout << endl;
}
};
int main()
{
int N = 9;
int i;
Graph diagraph(N);
diagraph.read_from_file("smallpopulation.dat");
diagraph.print_population();
diagraph.connections("smallconnections.dat");
diagraph.display_AdjList(diagraph.head[i]);
return 0;
}
解决方案
推荐阅读
- javascript - WebPack Only: Invariant Violation: ReactKonva 目前不支持文本组件。你的文字是:“”
- python - 如何解析多个文本文件并将所需的输出附加到单个文件中。(用于文档)
- python - 在python中读取多个json
- python - Plotly 袖扣钥匙
- osmnx - OSMnx SSLError: HTTPSConnectionPool(host='nominatim.openstreetmap.org', port=443):
- scala - 从pyspark中的文本文件中删除第一行和最后一行
- vaticle-typedb - grakn.ai 中的属性实例应该是单例的吗?
- excel - 运行时错误:范围自动筛选上的“1004”
- javascript - 使用 For 循环时图像未正确对齐
- android - ISO8601 到纪元毫秒