1

我正在分析一个数组,并使用一个结构来保存每个项目的位置和值,我想得到这个数组的三个最小值。这个问题是我必须忽略一个值,在这种情况下是'-5'。如果我试图忽略这个值,索引就会混乱,我不知道该怎么做。

这是我的尝试:

#include <cstdlib>
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <stdlib.h>

using namespace std;
typedef struct pair {
        int value, column;
    } Pair;
int cmp(const void *a, const void *b);

int main(int argc, char** argv) {

    Pair data_pair[8];

    int row[8] = {0, 3, 1, -5, 1, 2, 3, 4};
    for (int i=0;i<8;++i){
        if (row[i] != -5){ // Ignore the value -5 from the array
              data_pair[i].value = row[i];
              data_pair[i].column = i;
        }    
    }

    printf("\n\nThe three minimum values of this line are:");
    qsort(data_pair, 8, sizeof(Pair), cmp);
    for(int i=0;i<3;++i)
        printf("\nvalue = %d, column = %d", data_pair[i].value, data_pair[i].column);

    return 0;
}

 int cmp(const void *a, const void *b){
     Pair *pa = (Pair *)a;
     Pair *pb = (Pair *)b;
     return pa->value - pb->value; }

这是我的出口:

该行的三个最小值是:
value = 0, column = 0
value = 0, column = 0
value = 1, column = 4

当所需的解决方案是:

此行的三个最小值是:
value = 0,column = 0
value = 1,column = 2
value = 1,column = 4

我做错了什么?我想要一个解决方案,只需更改暴露代码的某些部分。
提前致谢

4

2 回答 2

4

Your issue at hand stems from using a shared index i and sorting the array regardless of how many items you actually have in the array (e.g. passing 8 unconditionally as the size).

By not setting the values at all indexes in data_pair, you're sorting some garbage results in the mix!

So you can use a second indexer with data_pair to help filter the results:

/* somewhere above: int j; */
for (i=0, j=0;i<8;++i){
    if (row[i] != -5){ // Ignore the value -5 from the array
        data_pair[j].value = row[i];
        data_pair[j].column = i;
        j++; /* indexes data_pair */
    }    
}

Now j will contain the count of found Pairs in data_pairs:

/* j substitutes for an explicit 8 */
qsort(data_pair, j, sizeof(Pair), cmp);
于 2013-05-20T14:44:54.193 回答
1
if (row[i] != -5){ // Ignore the value -5 from the array
    data_pair[i].value = row[i];
    data_pair[i].column = i;
} else {// add
    data_pair[i].value = INT_MAX;//#include <limits.h>
    data_pair[i].column = i;
}
于 2013-05-20T14:45:14.527 回答