如何从C中的2D数组中删除一行? [英] How to delete a row from a 2D array in C?

查看:75
本文介绍了如何从C中的2D数组中删除一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从矩阵中删除特定行并保持相同顺序?示例:

How do I remove a specific row from a matrix, keeping the same order? Example:

1 1 1
2 2 2
3 3 3

假设我需要删除所有偶数元素的行,因此删除后的行应类似于:

Let's say I need to remove the row with all even elements, so after deleting it should look like:

1 1 1
3 3 3

我尝试自己编写代码(条件与我上面提到的不同!),但实际上无法正常工作:

I tried writing code myself, (condition not the same as i mentioned above!) but it doesn't actually work properly:

for (i = 0 ; i < no_of_rows ; i++) { 
    if (abs(prosjeci[i] - prosjek) < 0.1) { /* condition */
        for (k = i ; k < no_of_rows - 1 ; k++) {
            for (j = 0 ; j < no_of_columns ; j++) {
                matrica[k][j] = matrica[k+1][j];
            }
        }
       i--;
       no_of_rows--;
    }
}

推荐答案

您的方法不起作用,因为您修改了矩阵,更新了 i 索引和行数 no_of_rows进行相应操作,但无法更新单独的数组 prosjeci .每当一行与过滤器匹配时,矩阵中的所有后续行都会被删除.

Your method does not work because you modify the matrix in place, update the i index and the number of rows no_of_rows accordingly, but fail to update the separate array prosjeci. Whenever a row matches the filter, all subsequent rows in the matrix are removed.

您可以通过为矩阵和过滤器数组使用单独的索引来解决此问题:

You can fix this problem by using a separate index for the matrix and the filter array:

int ii;  // index into the prosjeci array.

for (i = ii = 0; i < no_of_rows ; i++, ii++) { 
    if (abs(prosjeci[ii] - prosjek) < 0.1) { /* condition */
        for (k = i; k < no_of_rows - 1; k++) {
            for (j = 0; j < no_of_columns; j++) {
                matrica[k][j] = matrica[k+1][j];
            }
        }
        i--;
        no_of_rows--;
    }
}

或者,如果可以更新过滤阵列,则可以执行以下操作:

Alternately, if you can update the filtering array, you can do this:

for (i = 0; i < no_of_rows ; i++) { 
    if (abs(prosjeci[i] - prosjek) < 0.1) { /* condition */
        for (k = i; k < no_of_rows - 1; k++) {
            for (j = 0; j < no_of_columns; j++) {
                matrica[k][j] = matrica[k+1][j];
            }
            prosjeci[k] = prosjeci[k+1];
        }
        i--;
        no_of_rows--;
    }
}

这篇关于如何从C中的2D数组中删除一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆