[英]Comparing contents of two std::lists
我在這里嘗試做的是比較下面兩個類似的結構列表。 如果兩個人共享至少3個插圖,則應將它們配對在一起並放入配對列表中。 我先從列表中的第一個女孩開始,然后將其與男孩進行比較,如果找到一對,則將它們放入一個對列表中,並將其從各自的男孩列表/女孩列表中刪除。
struct Person {
char name[30];
enum gendertype gender;
TableOfIntrests intrests; //The tableofintrests consists of an array with 6 containters representing six diffrent intrests.
};
無論如何,我遇到的問題是該程序在匹配人員並創建配對的大約50%的時間內都能正常工作。 其他〜50%我收到一條錯誤消息,提示“列表迭代器不可取消”。 我有Google錯誤消息,但我不知道該怎么辦。 也許我在想是完全錯誤的,或者可以通過更好的方法來完成,我不知道,但是任何反饋都是值得的。
void pair_together(Personlist *girllist, Personlist *boylist, Pairlist *pairlist, int least_number_of_intrests)
{
int equal_intrests = 0;
Pair pair;
Person p, p2;
int testcount3=0;
std::list<Person>::iterator i = girllist->begin();
std::list<Person>::iterator end = girllist->end();
std::list<Person>::iterator i2 = boylist->begin();
std::list<Person>::iterator end2 = boylist->end();
while ((i != end))
{
testcount3=0;
if(i2==end2)
break;
equal_intrests = number_of_equal_intrests(i->intrests, i2->intrests); //number_of_equal_intrests return the number of intrests that the two persons shares.
if(equal_intrests >= least_number_of_intrests)
{
printf("%s + %s, ", i->name, i2->name);
printf("%d\n", equal_intrests);
equal_intrests =0;
create_person(&p, i->name, i->gender);
create_person(&p2, i2->name, i2->gender);
create_pair(&pair, p, p2);
pairlist->push_back(pair);
i =girllist->erase(i);
i2 =boylist->erase(i2);//--
i2=boylist->begin();
testcount3=1;
}
else if(testcount3!=1)
{
i2++;
}
if((i2==end2) && (equal_intrests < least_number_of_intrests))
{
i++;
i2=boylist->begin();
}
if(number_of_intrests(i->intrests) <least_number_of_intrests)//number_of_intrests returns how many intrests a person have, so if the person have less intrests than least_number_of_intrests the program just skips to the next person.
{
i++;
}
}
}
到最后你有這個
if((i2==end2) && (equal_intrests < least_number_of_intrests))
{
i++;
i2=boylist->begin();
}
if(number_of_intrests(i->intrests) <least_number_of_intrests)//number_of_intrests ...
{
i++;
}
在第二個if中,您不必檢查i!=end
是否可以,所以i->intrests
很可能會引起問題。 嘗試這個
if((i!=end) && number_of_intrests(i->intrests) <least_number_of_intrests)//number_of_intrests ...
{
i++;
}
您在遍歷列表時從列表中擦除,這會使迭代器感到困惑。 而是復制列表。 遍歷原件,但從副本中刪除。 完成后,丟棄原件並保留副本。
編輯:您不必制作副本; 您對重置“ i”迭代器的方式是正確的:這是安全的。 但是,從列表中刪除時,您確實需要為“ end”變量設置一個新值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.