3

我有这个代码:

#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) {
                 ..........
            }

    }
}

这里有问题。它说

'it = (((Graph*)this)->Graph::graph + ((unsigned int)(((unsigned int)i) * 12u)))->std::vector 中的 'operator=' 不匹配<_Tp, _Alloc>::以 _Tp = std::list, _Alloc = std::allocator >, std::vector<_Tp, _Alloc>::iterator = __gnu_cxx::__normal_iterator*, std::vector >,开头,类型名 std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer = std::list*' DejkstraAlg.cpp

谢谢 最好的

4

4 回答 4

4

graph是指向向量的指针,而不是向量。要么将其声明为向量,要么使用(*graph)[i].begin().

于 2013-10-29T10:44:01.673 回答
4

改成

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;
        }
    }
}
于 2013-10-29T10:51:21.383 回答
1

graph是一个指向向量的指针,也用来比较迭代器end()operator!=代替operator<

 for (it = (*graph)[i].begin(); it != (*graph)[i].end(); ++it)
 //                                ^^^

最好只写:

vector <list<int>> graph;
于 2013-10-29T10:47:09.813 回答
0

该错误指向您尝试将值分配给列表元素的statemenet(您没有显示)。我想你忘记了*它有指向 int 的指针类型。所以而不是

*it = value;

你必须写

**it = value;
于 2013-10-29T10:48:13.290 回答