在结构数组中查找重复项

时间:2017-03-21 01:52:23

标签: qt

我正在使用QT搜索结构中的重复条目。我有一个结构如下:

struct information{
QString fname;
QString lname;
QString gender;
QString age;
QString cod;

};

我这里有这个代码,它对结构中的每个变量都有bool变量,如果两个数组中的数据相同,则将bool值更改为true,并检查所有bool值是否为true并打印出两个重复的行。

for (int i=0; i<numlines; i+=1){
    for (int j=i+1; j<numlines; i+=1){
        bool fname = false;
        bool lname = false;
        bool age   = false;
        bool cod   = false;
        bool gender= false;

        if (person[i].fname == person[j].fname){
            fname = true;
            //qDebug() <<fname;
        }
        if (person[i].lname == person[j].lname){
            lname = true;
            //qDebug() <<lname;
        }
        if (person[i].gender == person[j].gender){
            gender = true;
            //qDebug() <<gender;
        }
        if (person[i].age == person[j].age){
            age = true;
            //qDebug() <<age;
        }
        if (person[i].cod == person[j].cod){
            cod = true;
            //qDebug() <<cod;
        }
        if (fname==true && lname==true && gender==true && age==true && cod==true){
            //print out where duplicate are.
            //duplicates at line i+1 and j+1

        }
    }
}

当我点击我的重复检查按钮激活代码时,它进入循环一次并意外终止程序。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

for (int i=0; i<numlines; i+=1){
    for (int j=i+1; j<numlines; i+=1){
        //                      ^

简单问题(可能是cut'n'paste错误) - 您需要增加j,而不是i

而且,顺便说一句,你可能会重构你的代码以使其更简单一些,因为如果任何字段匹配,你可以移动到下一个,类似于(伪-code):

for i = 0 to (sz - 2) inclusive:
    for j = (i + 1) to (sz - 1) inclusive:
        if person[i].fname  != person[j].fname:  continue
        if person[i].lname  != person[j].lname:  continue
        if person[i].age    != person[j].age:    continue
        if person[i].cod    != person[j].cod:    continue
        if person[i].gender != person[j].gender: continue

        // they're all equal at this point, log the fact.

这消除了对那些布尔变量的需要。

但是,如果你决定保留布尔值,你可以通过仔细选择他们的名字来使你的代码更具可读性。我倾向于选择布尔值,例如customerIsDeadmanagerHasPsychopathicTendencies。这样,在阅读代码时,它们“流动”更容易:

if (sameFName && sameLame && sameGender && sameAge && sameCod) {

你通常应该从不将布尔值与true或false进行比较,因为这只会给你另一个布尔值,并且根据reductio ad absurdum,你在哪里停止?

if ((((x == true) == true) != false) == true) ...
相关问题