Ad

C++: Nested Lists: How To Add An Item To A List Of Lists

- 1 answer

I am new on the board. I am using MS VS2008. 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:

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++ )
    {
    //incorrect
    //list<item> listEntry = *WholCompIter;
    //instead use:
    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

        }
    }
}
    //incorrect. 
//for(list<item>::iterator i=division2.begin(); i!=division2.end();++i)
//  cout<<i->name<<" "<<i->age<<endl;
    //instead use:
    for ( WholCompIter = WholeCompany.begin(); WholCompIter != WholeCompany.end(); WholCompIter++ )
{
    list<item>listEntry = *WholCompIter;

    for ( itemIter = listEntry.begin(); itemIter != listEntry.end(); itemIter++ )
    {   
    cout<<itemIter->name<<" "<<itemIter->age<<endl; 

    }
    cout<<endl; cout<<endl;
}
return 0;
}
Ad

Answer

You're just creating a copy here:

list<item> listEntry = *WholCompIter;

Instead, you need a reference:

list<item>& listEntry = *WholCompIter;

Also, you are printing from division2 in the loop at the bottom. Remember that WholeCompany is only a copy of division2 at the initialization. Since you've modified WholeCompany via the reference above, you need to access WholeCompany in the output loop at the bottom.

Ad
source: stackoverflow.com
Ad