iterator to access list
-
Hello,
I have some problems to access the list by iterator accordingly.
1. The list 'mylist_' and struct 'i' have to be redefined in a class file. Should it be done once in a header file? I have tried but have got a Segmentation fault error.
2. When I call the function 'list()', I would like to append a new entry to the list. The list size should grows up while calling list(). But this never happens, mylist_size() is always 1.
3. In the function 'getlist()', the iterator shows strange values of the list even it works fine in the function 'list()'.
Herewith, I attached an example of my code. Any suggestion, I am very welcome to hear

#aaa.h struct mystruct { double x double y } class aaa { public : void list(); void getlist(); list< struct mystruct > mylist_; struct mystruct i; }#aaa.cc void aaa::list(){ list< struct mystruct > mylist_; struct mylist i; i.x = 10.0; i.y = 20.0; mylist_.push_back(i); list< struct mystruct >::iterator it; for(it = mylist_.begin() ; it != mylist_.end() ; it++) { cout<< it->x << " , "<< it->y << endl; <-- ok!! } } void aaa::getlist(){ list< struct mystruct >::iterator it; for(it = mylist_.begin() ; it != mylist_.end() ; it++) { cout<< it->x << " , "<< it->y << endl; <-- strange values!! } }
-
Please, for readability of your code, activate BBCode in your postings and use the cpp-Tags instead of code-tags to switch on C/C++ syntax highlighting.
- the variables i and mylist_ should be made private members of your class aaa (granting public access to class member variables breaks encapsulation)
- unlike in C, in C++ there is no need to qualify mystruct as struct everytime. That means, list<mystruct> is sufficient and the declarations of i can (or should) be abbreviated tomystruct i;because mystruct is a complete type specifier on its own.
- the definition of mylist_ in aaa::list() defines a local variable, so the name of the member aaa.mylist_ is hidden. this is probably NOT what you want. The same applies to mystruct i. The result is that you construct a local struct, stuff it in the local list and do the output. After that at the end of aaa::list() both local variables are destroyed. Therefore, when calling aaa::getlist() that method accesses the aaa member variables that have never been touched.
what actually confuses me is that you seem to get into the for-loop inaaa:getlist(). As I said, you never touched the member mylist_ (you only modified the local variable mylist_ in aaa::list()). When you say mylist_.size() is 1 everytime that means you must have put something into the list in aaa's constructor - and the "strange values" in getlist() are those values from the ctor.
-
Please read first the examples of the reference:
http://www.cplusplus.com/reference/stl/list/Or you can google other examples with list or other keywords.
list< struct mystruct > mylist_;You don't have to write the struct here. You just have to use the keyword struct in a definition.
list< mystruct > mylist_;Would do this.