繁体   English   中英

迭代向量c ++中的列表

[英]Iterate over the lists in vector c++

我有这个代码:

#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)中不匹配'operator =' - > Graph :: graph +((unsigned int)(((unsigned int)i)* 12u))) - > std :: vector <_Tp,_Alloc> ::开始于_Tp = std :: list,_Alloc = std :: allocator>,std :: vector <_Tp,_Alloc> :: iterator = __gnu_cxx :: __ normal_iterator *,std :: vector>>, typename std :: _ Vector_base <_Tp,_Alloc> :: _ Tp_alloc_type :: pointer = std :: list *'DejkstraAlg.cpp

谢谢你

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

改成

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;
        }
    }
}

graph是指向矢量的指针,也为了将迭代器与end()进行比较,请使用operator!=代替operator<

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

更好的只是写:

vector <list<int>> graph;

错误会导致状态网(您未显示),您尝试将值分配给列表的元素。 我想你忘了*它有指向int的指针。 而不是

*it = value;

你必须写

**it = value;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM