C:扫描arrays时忽略一个值
我正在分析一个数组,并使用结构来保存每个项的位置和值,我想得到这个数组的三个最小值。 这个问题是我在这种情况下忽略一个值’-5’。 如果我试图忽略这个值,索引会搞砸,我不知道该怎么做。
这是我的尝试:
#include #include #include #include #include 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;ivalue - 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
我做错了什么? 我想有一个解决方案只是改变暴露代码的一些部分。
提前致谢
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 data_pair[i].column = i; }
您手头的问题源于使用共享索引i
并对数组进行排序,无论您在数组中实际拥有多少项(例如,无条件地传递8
作为大小)。
通过不在data_pair
中的所有索引处设置值,您将在混合中对一些垃圾结果进行排序!
因此,您可以使用带有data_pair
的第二个索引器来帮助过滤结果:
/* 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 */ } }
现在j
将包含data_pair
中找到的Pair
的计数:
/* j substitutes for an explicit 8 */ qsort(data_pair, j, sizeof(Pair), cmp);