I have created a Vector of pointers to a class called Food
vector<Food*> items;
The class looks like the following:
class Food
{
private:
string name;
int month;
int year;
public:
void display()
{
cout << name << " - " << month << "/" << year << endl;
}
}
I then have created a function to prompt these items
void promptInventory(vector<Food*> &items)
{
string name;
int month;
int year;
do
{
cout << "Enter item name: ";
getline(cin, name);
if (name != "quit")
{
cout << "Enter expiration month: ";
cin >> month;
cout << "Enter expiration year: ";
cin >> year;
cin.ignore();
Food * food = new Food;;
food->setName(name);
food->setMonth(month);
food->setYear(year);
items.push_back(food);
}
}
while (name != "quit);
I'd like to iterate through the vector of pointers and call the display function for all the items but I am unable to dereference them using iterators.
How would I be able to sucessfully iterate through these pointers and call the display function?
Unfortunately,
vector<Food*>::iterator iter = items.begin();
while (iter < items.end())
{
cout << *iter->display() << endl;
}
Results in:
error: request for member ‘display’ in ‘* iter.__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator-><Food**, std::vector<Food*> >()’, which is of pointer type ‘Food*’ (maybe you meant to use ‘->’ ?)
cout << *iter->display() << endl;
Thank you!
See Question&Answers more detail:os