iterator to access STL 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 :)

1
2
3
4
5
6
7
8
9
10
11
12
#aaa.h
struct mystruct {
double x
double y
}
class aaa {
public :
void list();
void getlist();
list< struct mystruct > mylist_;
struct mystruct i;
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#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!!
}
}
Last edited on
Please post your original code. There are many grammatical errors in the above code that would prevent it from compiling, so I can't be sure how close to accurate the example code is.

But I can say this, at least:

aaa::list() is redeclaring mylist_, which shadows the mylist_ data member in the object. Thus aaa::list() operates on its local version of mylist_, which then promptly gets destroyed when the function terminates. So seeing just the code you posted above, I would expect that aaa::getlist() would always do nothing because I don't see any code that actually inserts into the mylist_ member of aaa.
Topic archived. No new replies allowed.