In C++ Programming Language! Inventory operator + (const Inventory &inv1, const
ID: 3758696 • Letter: I
Question
In C++ Programming Language!
Inventory operator + (const Inventory &inv1, const Inventory &inv2)
{
Inventory newinv;
/*code*/
return newinv;
}
INFO:
I have a struct -> struct VARIABLES {string name; int productCount; double unitPrice; }
Inv1.array:
Apples (name) 30 (productCount) 10 (unitPrice)
Oranges 20 11
inv2.array:
Apples 25 9
Oranges 25 15
Grapes 50 1
The operator + function is a friend function. It takes two "inv" (inv1 and inv2) which have "n" (length of pointer array) "array" (the pointer array). The function should go add them together so that the the output is:
newinv.array:
Apples 55 9
Grapes 50 1
Oranges 45 11
There should be no doubles in the final list and if there are doubles in the orginial list the productCount adds together while the unitPrice takes the lesser value of the two.
I just can't wrap my head around how to do this! Can you?
Explanation / Answer
Inventory operator + (const Inventory &inv1, const Inventory &inv2)
{
Inventory newinv;
for(int i=0; i<inv1.n; i++) {
newinv.n++;
newinv.array = (Inventory *)realloc(newinv.array, sizeof(newinv.array)*newinv.n)
newinv.array[newinv.n-1].name = inv1.array[i].name;
newinv.array[newinv.n-1].productCount = inv1.array[i].productCount;
newinv.array[newinv.n-1].unitPrice = inv1.array[i].unitPrice;
}
for(int i=0; i<inv2.n; i++) {
int flag = 0;
for(int j=0; j<newinv.n; j++) {
if(newinv.array[j].name == inv2.array[i].name) {
flag = 1;
newinv.array[j].productCount += inv2.array[i].productCount;
newinv.array[j].unitPrice = inv2.array[i].unitPrice < newinv.array[j].unitPrice ? inv2.array[i].unitPrice : newinv.array[j].unitPrice;
break;
}
}
if(flag == 0) {
newinv.n++;
newinv.array = (Inventory *)realloc(newinv.array, sizeof(newinv.array)*newinv.n)
newinv.array[newinv.n-1].name = inv2.array[i].name;
newinv.array[newinv.n-1].productCount = inv2.array[i].productCount;
newinv.array[newinv.n-1].unitPrice = inv2.array[i].unitPrice;
}
}
return newinv;
}