首页 > 解决方案 > 匹配数组中的元素

问题描述

所以基本上我的问题是我有一个排序的整数数组和一个称为产品的结构数组。

结构:

typedef struct product 
{
   int ident;/*idp of a product*/
   char desc[64]; /* string that describes a product eg. "bread" */
   int price;  /* price of the product*/
   int weight; /* weight of the product eg. 2kg */
   int quant; /* quantity of the product in stock */
   int state_prod;/*state of a product, if its 1 its in the system else is 0 and is not in the system*/
}product;

数组:

product p1 = {0,"pao",2,2,200,1};
product p2 = {1,"ovos",1,1,100,1};
product p3 = {2,"iscas",3,3,300,1};
product p4 = {3,"bacon",2,5,400,1};
product p5 = {4,"abacate",2,6,500,1};

product system[5] = {p1,p2,p3,p4,p5};

int price[5] = {1,2,2,2,3};

我想要的是在每个产品中创建一个产品数组,价格与价格数组中的 int 匹配,如果价格相同,我希望将其与 ident 对应。

例如:

int price_og[5] = {2,1,3,2,2};

product system[5] = {p1,p2,p3,p4,p5};

//after sorting the pirce_og array i get

int new_price[5] = {1,2,2,2,3}

// What i want as a result is this

product new_system[5] = {p2,p1,p5,p4,p3};

//new_system is the array of products that match the prices of new_price

问题是我使用的这个函数可能是简单的错误,我似乎不知道它是什么

功能:

void align_prod(product a[],int b[],product c[]){
int i = 0;
while (i<5)
{
    if ((a[i].price == b[i]) && (a[i].ident == i))
    {
        c[i] = a[i];
        i++;
    }
    else
    {
        i++;
    }
}
}

认真的任何帮助将不胜感激。

标签: carraysfunction

解决方案


您想找到价格相同的产品。这意味着您可能会在某些时候进入else-statement并且您会这样做i++,这意味着您正在跳过 array 的某些元素c。对数组使用另一个计数器,c例如:

void align_prod(product a[],int b[],product c[]){
int i = 0 , j = 0;
while (i<5)
{
    if ((a[i].price == b[i]) && (a[i].ident == i))
    {
        c[j] = a[i];
        i++;
        j++;
    }
    else
    {
        i++;
    }
}
}

推荐阅读