List有2个元素,但迭代器只返回1个元素

时间:2018-04-15 11:03:00

标签: list c++11 iterator

我正在实现图形,我添加了顶点0,1,2。边缘看起来像0-1,0-2。 问题是我想迭代抛出所有顶点的所有邻居。代码bellow返回每个顶点的邻居数。它返回正确的数字,但是对于顶点0,它只会抛出一次迭代,甚至是对于vertex0的GetNeighbours.size()返回2.任何帮助?

// Main.cpp
std::list<Vertex> l = graph->GetAllVertexes();
std::list<Vertex> l2; // ---- IT WORKED AFTER THIS
std::list<Vertex>::iterator it2;
std::list<Vertex>::iterator it3;
for (it2 = l.begin(); it2 != l.end(); ++it2)
{
    cout << "Vertex: " << it2->GetId() << "\n";
    cout << "Number of neighbours: " << it2->GetNeighbours().size() << "\n";
    l2 = it2 ->GetNeighbours();                    // ---- IT WORKED AFTER THIS
    for (it3 = l2.begin(); it3 != l2.end(); ++it3) // ---- IT WORKED AFTER THIS
    {
        //cout << "iteration\n";
        cout << it3->GetId() << " ";
    }
    cout << "\n";
}
--------------------------------------------------
// Vertex.cpp
#include "Vertex.h" 
#include <iostream>
#include <string>
using namespace std;

Vertex::Vertex(){}
Vertex::~Vertex(){}

Vertex::Vertex(long _id)
{
    id = _id;
}

Vertex::Vertex(long _id, string _data) 
{
    id = _id;
    data = _data;
}

long Vertex::GetId()
{
    return id;
}

string Vertex::GetData()
{
    return data;
}

void Vertex::AddNeighbourVertex(Vertex *vertex)
{
    std::list<Vertex>::iterator it;
    for (it = neighbours.begin(); it != neighbours.end(); ++it)
    {
        if (it->GetId() == vertex->GetId()) return;
    }
    neighbours.push_back(*vertex);
}

list<Vertex> Vertex::GetNeighbours()
{
    return neighbours;
}

enter image description here

1 个答案:

答案 0 :(得分:0)

list不能是Vertex list,请尝试Vertex* private static readonly log4net.ILog rootlog = log4net.LogManager.GetLogger("rootLogger"); rootlog.Info(string.Format("Service [{0}] has started.", this.ServiceName)); // info msg rootlog.Error(string.Format("Get Tasks Unsuccessfull: {0}", response.MessageValue)); // error msg

当您将邻居复制到列表中时,这是由于值语义造成的 它的邻居也被复制了。

有关其工作原理的示例,请参阅http://coliru.stacked-crooked.com/a/0ef4b53212d76607