使用 c 中的结构添加稀疏矩阵(三元组形式)

Addition of sparse matrix using structure in c(triplet form)

我目前正在做一道稀疏矩阵的加法题。我正在使用三元组形式制作稀疏矩阵。三联体形式是利用c中的结构

struct sparse
{
    int row;
    int col;
    int val;
};

但是在做这个稀疏矩阵问题时我遇到了一个问题,当我以递增顺序给出非零值的索引时,我的代码只显示正确的稀疏矩阵(例如(0 1 3),(1 2 5 ),(2 2 7) 等)否则它会显示不正确的 matrix.for 示例如果我给出像 (0 1 3),(2 2 7),(1 2 5) 等输入然后它显示错误的矩阵。如何解决这个问题,以便在任何索引顺序中都能给出正确的输出?

我已经添加了我的输入和结果输出。我已经为两个稀疏矩阵完成了此操作。

#include<iostream>
#include<cstdio>
struct sparse
{
    int row,col,val;
};
void readmat(sparse sp[])
{
    printf("enter total number number of rows ,column of matrix and total
    of nonzero values in this\n");             
    scanf("%d %d %d",&sp[0].row,&sp[0].col,&sp[0].val);
    printf("now start entering the values by specifying index 
    position\n");
    for(int i=1;i<=sp[0].val;i++)
        scanf("%d %d %d",&sp[i].row,&sp[i].col,&sp[i].val);
}
void displaymat(sparse sp[])
{
    int k=1;
    for(int i=0;i<sp[0].row;i++)
    {
        for(int j=0;j<sp[0].col;j++)
        {
             if(k<=sp[0].val&&i==sp[k].row&&j==sp[k].col)
             {
                 printf("%d\t",sp[k].val);
                 k++;
             }
             else
                 printf("0\t");
         }
         printf("\n");
    }

}
int main()
{
    struct sparse sp1[10],sp2[10],sp3[10];
    printf("for first matrix\n");
    readmat(sp1);
    printf("for second matrix\n");
    readmat(sp2);
    displaymat(sp1);
    printf("\n\n");
    displaymat(sp2);
    printf("\n\n");
    displaymat(sp3);
    return 0;
 }`

更新原答案:

未打印乱序值的原因是,当三元组形式的值指向更下方的元素时,for 循环会超过所有可能已打印的其他值。例如,在您的示例中,第三个元素位于 row=1,col=3,而第二个元素位于 row=2,col=2。这将导致外部 for 循环向下推进到第二行。在那个时间点,循环将不会返回并打印第一行。

一种方法是根据行和列排序,然后打印值。