我是董事会的新成员。我正在使用 MS VS2008。我正在学习列表列表。我正在尝试将元素添加到列表中的列表中。
我在我的程序中指出了我遇到问题的地方。当我调试它时,“beth”被添加到第二个列表(division2),但是当循环退出时,“beth”不在第二个列表中,即使我已经在嵌套循环之外声明了我的所有列表。
任何帮助将不胜感激。
这是代码:
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;
}