我正在实现一个图形的非常simpel模型,其中我有一个包含指向它的邻居的转发列表的结构。这些邻居依次是同一类型的结构。结构与forward_list指针本身
#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;
};
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;
}
if(!foundEmptyLine){
// processing vertexes
Vertex *vertex = new Vertex;
vertex->id = stoul(line);
graph.emplace(*vertex);
index.emplace_back(vertex);
}else{
// Processing relations
Edge edge = process_line(line);
Vertex* neighbor = index.at(edge.second);
// Lookup edge in index
index.at(edge.first)->_next.push_front(neighbor);
}
}
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){
// Print item.
cout << "Node: " << it->id << endl << "Neighbors:";
for(Neighbors::iterator neigh = it->_next.begin(); neigh != it->_next.end(); ++neigh){
// Print item.
cout << (*neigh)->id;
}
}
}
// Entry point.
int main() {
Graph graph;
Index index;
load_graph("graph_1.txt", graph, index);
print_graph(graph);
}
这一切都工作了,直到我尝试循环的顶点在图中,随后环顶点的所有邻居。 (print_graph函数)我得到这个错误:
error: no viable conversion from 'const_iterator' (aka '__forward_list_const_iterator *>') to 'Neighbors::iterator' (aka '__forward_list_iterator *>')
在此先感谢。
那里有循环?! –
Print_graph方法,应该已经提到它的确。 – Iso
它只是告诉你那里你需要做什么。你需要使用Neighbors :: const_iterator而不是迭代器。 – overseas