In: Computer Science
Give examples of a C++ program that allow users to manipulate (adding, removing, sort, etc.) a list of items. To start, you need to propose a problem that you would like to work on and you can't use TO-DO list.
We can take a problem as follows:
Suppose we have to create a list of phone numbers (contacts list) in a phone. Here, we can add numbers, remove numbers and sort numbers.
Given is the solution of the above problem in C++:
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector <int> numbers; //we create an empty vector named numbers
cout<<"Enter the operation you want to perform: "<<endl;
int c; //we declare int c to take input of the operation.
int x; //we declare x to take input of the number.
int f = 1; //we declare f to indicate whether the program has to be ended or not.
while(f == 1)
{
cout<<"(1). Add"<<endl; //displaying the menu.
cout<<"(2). Remove"<<endl;
cout<<"(3). Sort"<<endl;
cin>>c;
switch(c) //we pass c within the switch case.
{
case 1: //case in which user wants to add a number.
cout<<"Enter number to be added: ";
cin>>x;
numbers.push_back(x); //number is pushed back to the list.
break;
case 2: //case in which user wants to remove a number.
cout<<"Enter number to be deleted: ";
cin>>x;
for(int i=0;i<numbers.size();i++){
if(numbers[i]==x)
{
numbers.erase(numbers.begin()+i); //number is erased from the position where it is found.
}
}
break;
case 3: //case in which user wants to sort the list.
cout<<"The contact list has been sorted. "<<endl;
sort(numbers.begin(),numbers.end());
break;
default: //deafult case if user does not enter valid number.
cout<<"Enter valid number.";
}
cout<<"Do you want to perform another operation? If yes Enter 1: ";
cin>>x; //taking input in case the user wants to re-run the program.
if(x==1)
{
f = 1; //case when the user wants to re-run it.
}
else
{
f = 0; //case when the user wants to end the program.
}
}
return 0; //terminating the program.
}
Kindly like if this helps :)