Reputation: 6361
I am kind of new to c++ and got headache with this pointer and stuff!
I need to iterate through list of struct which is linked list, read the data of struct and pop that entry!
this my struct :
struct node {
map<string,double> candidates;
double pathCost;
string source;
node *next; // the reference to the next node
};
by reading this post I create my list like :
list<node*> nodeKeeper;
and then initialized the first value:
node *head;
head= new node;
head->pathCost = 0.0;
head->source="head";
head->next = NULL;
thin fill the list and struct :
for(unsigned int i = 0; i < sourceSentence.size(); i++){
node *newNode= new node; //create a temporary node
//DO STUFF HERE
//push currunt node to stack
nodeKeeper.push_back(newNode);
head = newNode;
}
now I have list of struct and I want to iterate through it and pop the elements:
for (list<node*>::const_iterator it=nodeKeeper.begin();it!=nodeKeeper.end();it++){
it->pop_front();
}
which gives me this error:
error: request for member 'pop_front' in '* it.std::_List_const_iterator<_Tp>::operator->()', which is of pointer type 'node* const' (maybe you meant to use '->' ?) make: *** [main3.o] Error 1
It looks like that my iterator points inside the list , not the list itself!
Can you tell me what is wrong here?!
Upvotes: 0
Views: 9178
Reputation: 96810
If all you need to do is remove the elements, use std::list::clear
:
nodeKeeper.clear();
To read the contents of the element, then remove, try this:
for (std::list<node*>::const_iterator it = nodeKeeper.begin(); it != nodeKeeper.end(); ++it) {
std::cout << (*it)->source;
// do more reading
nodeKeeper.pop_front();
}
or with C++11:
for (const auto& a : nodeKeeper) {
std::cout << a->source;
nodeKeeper.pop_front();
}
Upvotes: 2
Reputation: 508
If your goal is to have a single list of your node struct, there is no need to manage next pointers your self. Inserting would stay the same (minus the head =
line)
To pop all element of the list you would do something like
int sizeOfList = nodeKeeper.size();
for( int i =0; i < sizeOfList; i++) {
//if you want to do something with the last element
node * temp = nodeKeeper.back();
//do stuff with that node
//done with the node free the memory
delete temp;
nodeKeeper.pop_back();
}
Compiling/running example here: http://ideone.com/p6UlyN
Upvotes: 2