我有这段代码:
#include <iostream>
#include <vector>
#include <list>
using namespace std;
class Graph {
public:
//Create graph with n nodes
Graph(int size);
~Graph();
//Initialize graph
void InitializeGraphWithRandomNum();
private:
vector <list <int*> > *graph;
};
void Graph::InitializeGraphWithRandomNum() {
//Here I want to iterate
for (int i=0; i< graph->size(); i++) {
std::list <int*>::iterator it;
for (it = graph[i].begin(); it< graph[i].end();++it) {
..........
}
}
}
这里有些不对劲。它说
'= =(((图*)这里)''运算符='不匹配 - &gt;图形::图形+((无符号整数)(((unsigned int)i)* 12u))) - &gt ; std :: vector&lt; _Tp,_Alloc&gt; ::以_Tp = std :: list开头,_Alloc = std :: allocator&gt ;, std :: vector&lt; _Tp,_Alloc&gt; :: iterator = __gnu_cxx :: __ normal_iterator *,std :: vector&gt; &gt;,typename std :: _ Vector_base&lt; _Tp,_Alloc&gt; :: _ Tp_alloc_type :: pointer = std :: list *'DejkstraAlg.cpp
谢谢 最好
答案 0 :(得分:3)
graph
是指向矢量的指针,而不是矢量。要么将其声明为向量,要么使用(*graph)[i].begin()
。
答案 1 :(得分:3)
更改为
void Graph::InitializeGraphWithRandomNum()
{
typedef list<int*> int_list;
typedef vector<int_list> int_list_vector;
for (int_list_vector::iterator vectit = graph->begin(); vectit != graph->end(); ++vectit)
{
for (int_list::iterator listit = vectit->begin(); listit != vectit->end(); ++listit)
{
int* value = *listit;
}
}
}
或者更干净,如果您有C ++ 11(不包含在您的标签中,但可能对其他人有用):
void Graph::InitializeGraphWithRandomNum()
{
for (auto vectit = graph->begin(); vectit != graph->end(); ++vectit)
{
for (auto listit = vectit->begin(); listit != vectit->end(); ++listit)
{
int* value = *listit;
}
}
}
如果你进入C ++ 11非成员的开始/结束,许多C ++(像我一样)都支持:
void Graph::InitializeGraphWithRandomNum()
{
for (auto vectit = begin(*graph); vectit != end(*graph); ++vectit)
{
for (auto listit = begin(*vectit); listit != end(*vectit); ++listit)
{
int* value = *listit;
}
}
}
答案 2 :(得分:1)
graph
是指向vector的指针,也是将迭代器与end()
比较使用operator!=
而不是operator<
for (it = (*graph)[i].begin(); it != (*graph)[i].end(); ++it)
// ^^^
最好写一下:
vector <list<int>> graph;
答案 3 :(得分:0)
错误导致状态网(您未显示),您尝试将值分配给列表的元素。我想你忘了*它有指向int的指针。 而不是
*it = value;
你必须写
**it = value;