c++ - 比较两个 std::lists 的内容

标签 c++ list compare

我在这里要做的是比较两个结构列表,如下所示。如果两个人至少有 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% 我收到一条错误消息,指出“列表迭代器不可取消引用”。我用谷歌搜索了错误消息,但我不知道该怎么做。也许我的想法完全错误,或者可以用更好的方式来完成,我不知道,但欢迎任何反馈。

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++;            
}

关于c++ - 比较两个 std::lists 的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18060623/

相关文章:

c++ - 为什么在核心转储中得到 "first/second chance not available"

Python:确定列表中相等项目序列的长度

sql - 我可以比较 MySQL 枚举吗?

Java:比较具有不同顺序的关键字的字符串

javascript - 比较两个对象以覆盖其中一个的值

c++ - 链表的 Lambda 长度

c++ - 为什么以下不等式在 C++ 中计算为真?

c++ - 后缀评估,为什么推送函数不更新堆栈变量的顶部?

java - 列表和 map 的通用集合?

c# - 从列表中删除最近添加的项目