簡體   English   中英

C ++列表插入迭代器

[英]C++ List Insert Iterator

一個Family對象包含一個Person對象的鏈接列表,因此,在Family類中存在一個函數,用於將Person對象插入到名為people的ListedList中。

我在將某些“個人”對象添加到人員鏈接列表時遇到了麻煩。 我已經省略了許多其他函數,因為我(希望)能夠確定問題是在Family類的insertPerson()函數中發生的。

insertPacket()的for循環按預期遍歷每個“ Person”對象(請參見注釋的“ cout”)。 但是,如果在if語句中發生故障。

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

如果person_id小於鏈接列表中的get_person_id() ,它將執行並將其插入列表的開頭,但是如果不是,它將完全跳過它。

嘗試

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

std :: list根據鏈接插入是

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

您的基本錯誤在這里,在insertPerson

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

如果此人的ID大於當前列表中的所有成員,該怎么辦? 然后insert將永遠不會發生,因為您將到達end()並中斷循環。 這應該用於查找插入點,其中可以包括 end()

您可以執行以下操作找到合適的插入點:

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

請注意,這允許重復插入給定的ID。 不知道您是否在乎。 最后,插入Family存在相同的問題,因此您可能要在此之后進行修復。

祝你好運。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM