简体   繁体   中英

C++ List Insert Iterator

A family object contains a linked list of Person objects, and as such, a function exists within the Family class to insert Person objects into a ListedList called people.

I'm having some trouble where only certain Person objects are being added to the people linked list. I have omitted a number of other functions, as I was (hopefully) able to determine the problem is occurring within the insertPerson() function in the Family class.

The for loop within insertPacket() is looping through each 'Person' object as intended (refer to commented 'cout'). However, things break down in the if statement..

if (person_id < itr->get_person_id())
      {
         Person *psn = new Person(person_id, name);
         people.insert(itr, *psn);
         break;
      }

If a person_id is less than the get_person_id() in the linked list, it executes and inserts it at the beginning of the list, however if it is not, it just skips it entirely...

Try

   if (input_id < itr->get_familyid())
   {
         Family *fam = new Family(input_id);
         families.insert(itr, *fam);
         break;
   }

std::list insert according to this link is

iterator insert (iterator position, const value_type& val);

You're fundamental bug is here, in insertPerson :

for(itr = people.begin(); itr != people.end(); itr++)
{
    if (id < itr->get_person_id())
    {
        people.insert(itr, Person(id, text));
        break;
    }
}

What if the person's id is greater than all of the current list members? Then the insert will never happen as you will reach end() and break the loop. This should be used to find the insertion point, which can include end() .

You can find the proper insertion point doing this:

for(itr = people.begin(); itr != people.end(); itr++)
{
    if (itr->get_person_id() < id)
        break;
}
people.insert(itr, Person(id, text));

Note that this will allow duplicate insertions for a given id. Not sure if you care about that. Finally, the same problem exists for insertion of a Family , so you probably want to fix that after this.

Best of luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM