I’m having a bit of trouble trying to get class association’s to work correctly.
I have a vector of class objects, named Items. Each item has a values such as a name, price, etc. Inside the Items class there are setters and getters to change the values and to return them.
std::string choice; // users choice
ListOfOrders::iterator iter = orderList->end(); iter--;
// the last order inserted, ignore this this is used to get the last order so
//we can pass the items to it (the order class has a vector of pointers
//(items) that we are trying to pass to now.)
ListOfItems::iterator itemiter; // make the items iter
listItems(itemList); // function in the main that returns the list of items using the getters and a vector iterator.
while(choice != "x") // until the user quits
{
// here is my prob, ofc, i can just compare the users entered choice of item (name) to the iterator because thats just returning a pointer to the class object, what i need to do it call the getName() getter from each of the objects and comparer that
(*itemiter)->getName() = find (itemList->begin(), itemList->end(), choice);
if (itemiter == itemList->end())
{
std::cout << "sorry item not found please try again." << std::endl;
}
else
{
(*iter)->addItem(*itemiter); // pass the item object off to the order object's vector of items.
}
}
I know something like this(see below(haven’t compiled it, just quickly typed it to give you a idea)) could be used and it would work, but there must be a better way right?
std::string choice; // users choice
cin >> choice;
ListOfOrders::iterator iter = orderList->end(); iter--; // the last order inserted
if(lookForItem(choice))
{
std::cout << "Yes\n";
}
else
{
std::cout << "no\n";
}
bool lookForItem(std::string choice)
{
ListOfItems::iterator itemiter; // make the items iter
itemiter = itemList->begin();
while(itemiter != itemList->end())
{
if((*itemiter)->getName() == choice)
{
(*iter)->addItem(*itemiter);
}
iter++;
}
return false;
}
In modern C++, this is fairly simple with a lambda:
It’s not hard to spell out the lambda as a traditional predicate, of course: