Question

I have a Node class. It contains x,y coordinates, an id and a list of Node pointers which holds the adjacent nodes.

I am having problem with the list data structure inside the class. The printAdj() function works fine but I need to iterate through the adjacency list of a node from outside the class by acquiring adjList member using adjs() function.

class Node{
public:
    // constructors & destructors
    Node(double x, double y, unsigned id) : x_(x), y_(y), 
                                            id_(id) {}

    // setters & getters
    std::list<Node*> adjs() const   { return adjList;   }


    // member functions
    void addAdj(Node* n) { adjList.push_back(n); }

    void printAdj() const{
        for(std::list<Node*>::const_iterator it = adjList.begin(); 
                                             it != adjList.end() ; ++it){
            std::cout << "\t" << (*it)->id() <<  " " << std::endl;
        }
    }


private:
    std::list<Node*> adjList;
    double x_, y_;
    unsigned id_;
};

The outside loop runs forever.

list<Node*> RRT_graph;  //global

void print(){
    for(list<Node*>::const_iterator it = RRT_graph.begin() ;
                                    it != RRT_graph.end() ; ++it){

        cout << "Node ID: " << (*it)->id() << "\tX: " << (*it)->x() 
                                           << "\tY: " << (*it)->y() << endl;

        cout << "\tAdjacency List:" << endl;
        (*it)->printAdj();    // member function correctly prints adjacency list

        // nothing wrong with the size, it displays correctly
        cout << "-----------------------------------" << endl;
        cout << "(" << (*it)->adjs().size() << ")" << endl; 

        // but when the list is looped, it goes forever.
        unsigned count = 0;            
        for(list<Node*>::const_iterator ite = (*it)->adjs().begin() ; 
                                        ite != (*it)->adjs().end() ; ++ite)
            cout << count++ << endl;


}

Since two adjacency list printing loops are identical and only member function works, I suspect a scope issue here but I'm sort of lost.

What's wrong here?

Was it helpful?

Solution

Just return const reference in adjs(), it should work. Currently it is returning a copy, hence when you take iterator in (*it)->adjs().begin() and in (*it)->adjs().end(), it gives iterators to different copies

    const std::list<Node*>& adjs() const   { return adjList;   }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top