このコードはかなり神経質になっています。しばらくの間それをデバッグしていた、私はC++にどのようにしているかを信じていません。ストラクチャフォワードリスト項目が消滅しますか?
私はいくつかの単純なアルゴリズムを実行するためにグラフをモデル化しようとしていますが、うまくいかないようです。すべての頂点には、近隣の要素への順方向リストが含まれていますが、要素を挿入するときは明らかに存在します。その時、フォワードリストは空です。スコープが...ん運のいずれか。..既存の頂点への参照を維持するために、グラフを修正
#include <iostream>
#include <vector>
#include <set>
#include <forward_list>
#include <fstream>
using namespace std;
typedef struct Vertex Vertex;
struct Vertex {
unsigned id;
forward_list<Vertex*>_next;
bool operator < (const Vertex &other) const { return id < other.id; };
};
typedef set<Vertex> Graph;
typedef vector<Vertex*> Index;
typedef pair<unsigned, unsigned> Edge;
typedef forward_list<Vertex*> Neighbors;
// Function: process_line()
// Purpose: process a specific line from the file.
// Params: line to process
Edge process_line(string line){
unsigned vertex_from;
unsigned vertex_to;
int idx = line.find(" ");
vertex_from = (unsigned)stoul(line.substr(0, idx));
vertex_to = (unsigned)stoul(line.substr(idx+1, line.length()));
return make_pair(vertex_from, vertex_to);
}
// Function: load_graph()
// Purpose: load graph from file in relation
// Params: path, and reference to graph and index
bool load_graph(string file_path, Graph &graph, Index &index){
string line;
ifstream file(file_path);
bool foundEmptyLine = false;
if(file.is_open()){
while(getline(file, line)){
if(line.empty()){
foundEmptyLine = true;
continue;
}
if(!foundEmptyLine){
// processing vertexes
Vertex *vertex = new Vertex;
vertex->id = stoul(line);
graph.insert(*vertex);
index.emplace_back(vertex);
}else{
//Processing relations
Edge edge = process_line(line);
Vertex* neighbor = index.at(edge.second);
Vertex* source = index.at(edge.first);
// Lookup edge in index
source->_next.emplace_front(neighbor);
// ITEMS PRESENT! <----------------------
}
}
file.close();
}else{
cout << "Unable to open " << file_path;
return false;
}
return true;
}
void print_graph(Graph &graph){
for(Graph::iterator it = graph.begin(); it != graph.end(); ++it){
Neighbors neighs = it->_next;
cout << "Node: " << it->id << " neighbors: " neighs.empty();
cout << endl;
}
}
// Entry point.
int main() {
Graph graph;
Index index;
load_graph("graph_1.txt", graph, index);
print_graph(graph);
}
の
value_type
にイテレータを返す可能性がもう一度あなたの努力をありがとうございました。私はセットがベクトルに対抗する要素をコピーするという事実を忘れてしまった。それで、なぜリファレンスをセットに挿入すると全体が機能するのですか?私の作業バージョンでもconst_iteratorのヒントを使用しました。 – Isoインデックスにベクトルを使用し、グラフにはを、近隣にはforward_list を設定することをおすすめします。 –
overseas