繁体   English   中英

比较两个std :: lists的内容

[英]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.

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