In: Computer Science
Imagine you are writing a program to manage a shopping list. Each shopping list item is represented by a string stored in a container. Your design requires a print function that prints out the contents of the shopping list. Using a vector to hold the shopping list items, write a print function to print out the contents of a vector of strings. Test your print function with a main program that does the following:
Create an empty vector.
Append the items, "eggs," "milk," "sugar," "chocolate," and "flour"
to the list. Print it.
Remove the last element from the vector. Print it.
Append the item, "coffee" to the vector. Print it.
Write a loop that searches for any item whether it is present in
the vector or not.
Write a loop that searches for the item, "milk," and then remove it
from the vector. (You are permitted to reorder the vector to
accomplish the removal, if you want.) Print the vector.
Input:
sugar
Output:
eggs milk sugar chocolate flour
eggs milk sugar chocolate
eggs milk sugar chocolate coffee
present
eggs sugar chocolate coffee
Code:
#include <iostream>
#include<vector>
#include <string>
using namespace std;
void printShoppingList(vector<string> s)
{
for (auto i = s.begin(); i != s.end(); ++i) //iterate vector from start to end
cout<< *i<<" "; //print each item from vector
}
int main()
{
string str;
cout<<"Enter what you want to search ?\n"; //get item from user for searching
cin>>str;
vector<string> s;
s.push_back("eggs"); //push items into vector
s.push_back("milk");
s.push_back("sugar");
s.push_back("chocolate");
s.push_back("flour");
cout<<"\nInitial shopping list: \n"; //print initial shopping list
printShoppingList(s);
s.pop_back(); //popo last item
cout<<"\n\nAfter removing last item from shopping list: \n";
printShoppingList(s);
s.push_back("coffee"); //append item
cout<<"\n\nAfter appending coffee item in shopping list: \n";
printShoppingList(s);
int flag=0;
cout<<"\n\nFinding "<<str<<" item in shopping list: \n";
for (auto i = s.begin(); i != s.end(); ++i) {//iterate vector
if(*i==str){
flag=1; //item is found then set flag
cout<<"present";
}
}
if(flag==0) //if flag is not set then item is not found
cout<<"Not present";
cout<<"\n\nFind milk item and remove it from shopping list: \n";
for (auto i = s.begin(); i != s.end(); ++i) { //iterate vector
if(*i=="milk") //find item is present in list
s.erase(i); //if present then remove it here erase() function will remove element from vector by its index
}
printShoppingList(s);
return 0;
}
Output:
.