My current task is to make a list of ingredients for a cocktail, stored in a vector. If the ingredient, which the user types in is already in the vector, the counter increases (the ingredient's name and quantity is in a struct). Then, I must count from the total summary of the ingredients and the individual ingredients the percentage of the given ingredient in the "cocktail".
I have problem at counting the individual quantities. It works perfectly when I type in the ingredients in an order where no same ones follow each other. However, if I type the same ingredient after each other, the vector deems it as a new element and adds it to the back. Could you help me how to solve it?
#include <iostream>
#include <string>
#include <vector>
struct ingredient {
std::string name;
int quantity = 1 ;
// ..
};
// add the ingredient if it is not present, update its quantity otherwise
void add_item( std::vector<ingredient>& items, const std::string& name, int qty = 1 )
{
// range based loop: https://www.stroustrup.com/C++11FAQ.html#forfor( ingredient& ing : items ) { // for each item in the vector
if( name == ing.name ) { // note: name is case sensitive
// found the ingredient with this name
ing.quantity += qty ; // update its quantity
return ; // and we are done
}
}
// if we reach here, the ingredient was not found in the vector; add a new item
items.push_back( { name, qty } ) ;
}
int main() {
std::vector<ingredient> items ;
std::string name ;
while( std::cout << "ingredient (enter 'done' to quit): " && std::cin >> name && name != "done" )
add_item( items, name ) ; // default value for quantity is 1
// ...
}
Using std::map (with the name as the key) would be a good alternative.