【发布时间】:2014-04-20 22:52:01
【问题描述】:
好的,我无法打印结构列表中的值。打印列表(使用迭代器)的正常方式不起作用。这是我将文件读入列表的代码。
struct Edge{
map<char, string> edge;
int weight= -1;
Edge(){};
Edge(char v, string e, int w){
edge.insert(pair<char,string>(v,e));
weight = w;
}
};
int main(){
list<Edge> edges;
//Read in file//
string line;
char start;
vector<string> tokens;
if(!file.is_open()){
cout<<"Could not open file\n";
}else{
while(getline(file,line)){
tokens.clear();
start = line.front();
istringstream iss(line);
copy(istream_iterator<string>(iss),
istream_iterator<string>(),
back_inserter<vector<string>>(tokens));
for(int i = 1; i<tokens.size(); i+=2){
//cout << "Position: " <<i << " = " << tokens.at(i) <<endl;
//insert into edges list.
Edge e = Edge(start, tokens.at(i), stoi(tokens.at(i+1)));
edges.push_back(e);
}//end for
}//end while
}//end if-else
return 0;
}//end main
向量标记被正确读入。我用注释掉的 cout 检查了它。
该文件是一个图形文件,第一个元素是起始顶点,该行的其余部分使用边的结束顶点和边的权重进行格式化。
例如:
1 2 3 4 5
表示边 (1,2) 的权重为 3,边 (1,4) 的权重为 5。
我不知道我是否正确阅读了我的列表,因为我不知道如何打印出来。我将如何打印出我的列表边缘?
或者有没有更好的方法来设置我的结构?或许是另一个结构体作为边缘,然后是一个结构体与边缘和权重?
尝试打印,但无法正常工作。语法甚至不起作用。 :(
打印列表的常规方式。但不喜欢它,因为我有一个结构列表。
list<Edge>::iterator it;
for(it=edges.begin(); it!=edges.end(); it++){
cout << *it <<endl;
}//end for
这就是我在搜索时发现的。这就是我发现的。 C++ How to loop through a list of structs and access their properties 这是我的尝试。
//inside main
list<Edge>::iterator it;
for(int i = 0; i<edges.size(); i++){
for_each(edges.begin(), edges.end(), printEdges);
}//end for
//outside main
void printEdges(Edge &data){
cout << "( " << data.edge << " )"
<< ": Weight = " << data.weight <<endl;
}//end printEdges
谢谢。
【问题讨论】:
标签: c++ printing map struct hashtable