vector<fruit_t> cpy;
for (int i = 0; i < fruit.length(); i++) {
bool already_entered = false;
for (int j = 0; j < cpy.length(); j++) {
bool diff = false;
for (int k = 0; k < MAX_LENGTH; k++) {
if (cpy[j].fruit_name[k] != fruit[i].fruit_name[k]) {
diff = true;
}
}
if (diff == false) {
already_entered = true;
}
}
if (already_entered == true) {
continue;
}
float new_quantity = fruit[i].quantity;
for (int j = i + 1; j < fruit.length(); j++) {
bool diff = false;
for (int k = 0; k < MAX_LENGTH; k++) {
if (fruit[j].fruit_name[k] != fruit[i].fruit_name[k]) {
diff = true;
}
}
if (diff == false) {
new_quantity += fruit[j].quantity;
}
}
cpy.push_back(fruit_t());
for (int k = 0; k < MAX_LENGTH; k++) cpy[cpy.length() - 1].fruit_name[k] = fruit[i].fruit_name[k];
cpy[cpy.length() - 1].quantity = new_quantity;
cpy[cpy.length() - 1].price = fruit[i].price;
}
What this does:
We create a new vector that will only have once occurrence of each fruit name.
We loop through our original vector, each time checking if we have already processed the current fruit (we can do this by simply looping through our cpy array). Now, we loop through the rest of the vector with a nested for loop, and add to our new_quantity variable the sum of quantities that appear for that fruit later in our original vector. Finally, we create a new object and store our results in cpy.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…