Nested Lists: how to add an item to a list of Lists

Hi guys, I am new on the board.
I am learning about list of lists.
I am trying to add elements to a list which is part of a list of lists.

I have noted in my program where I am having a problem.
When I debug it, "beth" is being added to the second list (division2), but when the loop is exited, "beth" isn't in the second list even though I have declared all my lists outside of the nested loop.

Any help would be greater appreciated.

Here is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <list>
#include <iostream>
#include <string>

using namespace std;

struct item
{
	string name;
	int age;
};
int main()
{
	list<item> division1;
	list<item> division2;

	list< list<item> >WholeCompany;

	item s; 
	s.name="sandra"; s.age=43; division1.push_back(s);
	s.name="Marc"; s.age=19; division2.push_back(s);
	s.name="betty"; s.age=34;division2.push_back(s);

	WholeCompany.push_back(division1);
	WholeCompany.push_back(division2);
	
	list< list<item> >::iterator WholCompIter;
	list<item>::iterator itemIter;

	for ( WholCompIter = WholeCompany.begin(); WholCompIter != WholeCompany.end(); WholCompIter++ )
        {
        list<item> listEntry = *WholCompIter;

        for ( itemIter = listEntry.begin(); itemIter != listEntry.end(); itemIter++ )
        {	
			//MY ISSUE IS RIGHT HERE! How can I add the value to the list, but the list forgets it when it exit loop
			if(itemIter->name =="betty")
			{
				item s; s.name="beth"; s.age=65;
				listEntry.insert(itemIter,s);//problem is here.
                                //I have also tried
                                //listEntry.push_back(s) but the output doesn't show it
				
			}
		}
	}

	for(list<item>::iterator i=division2.begin(); i!=division2.end();++i)
		cout<<i->name<<" "<<i->age<<endl;

	return 0;
}
list<item> listEntry // in the "for" loop is local variable and just making another copy of the list.

get that list's memory and add it.

Topic archived. No new replies allowed.