C++ coding Create a class called NumberList that holds a user-defined maximum nu
ID: 3858090 • Letter: C
Question
C++ coding
Create a class called NumberList that holds a user-defined maximum number of integers in a vector. If more than the maximum number of integers is added an error message should be printed out. Write a method print_list that prints the numberof integers in the list and each number stored in the list. Create at least 2 NumberList objects, fill them, and print their contents. Include your NumberList class and print_list method below along with sample output. You should use good C++ object-oriented design principles, including using a separate .cpp & .h file for defining NumberList.
Explanation / Answer
#include <iostream>
#include <vector>
using namespace std;
class NumberList
{
protected:
vector<int> vec; // create a vector to store int
int max_val,val;
public:
NumberList(){}
void getmaxval()
{
cout << "Enter the size of vector "; //taking vector limit
cin>>max_val;
}
output:
void getvectinp()
{
cout << "Enter the values of vector ";
for(int i = 0; i < max_val; i++) // push the values into the vector
{
cin>>val;
vec.push_back(val);
}
}
void insertinp()
{
if (max_val<=vec.size()) //checking the limit of vector
cout <<"1"<< "current vector size = " << vec.size() <<" has reached the limit";
else if(max_val>vec.size())
getvectinp();
}
void disp()
{
for(int i = 0; i < max_val; i++) // display the values from the vector
{
cout << "values of vector [" << i << "] = " << vec[i]<<endl;
}
cout << " ";
}
};
int main()
{
NumberList ob1,ob2;
u_chc_lbl:
ob1.getmaxval();
ob1.insertinp();
ob2.getmaxval();
ob2.insertinp();
cout << " For object ob1 ";
ob1.disp();
cout << " For object ob2 ";
ob2.disp();
cout << "Press any number from 1 to 9 to continue or 0(zero) for exit ";
int chc;
cin>>chc;
if (chc>=1 && chc<=9)
goto u_chc_lbl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.