Class Implementation and Vector Loops Part A Implement all m
Class Implementation and Vector Loops
Part A
Implement all member functions of the following class:
class Person
{
public:
Person();
Person(string pname, int page);
string get_name() const;
int get_age() const;
void set_name(string pname);
void set_age(int page);
private:
string name;
int age; //0 if unknown
};
Part B
Write a loop that fills a vector V with ten random numbers between 1 and 100.
Part C
Write a loop that fills a vector V with ten different random numbers between 1 and 100.
Solution
#include <iostream>
#include <vector>
#include <time.h>
#include <stdlib.h>
#include <algorithm>
using namespace std;
//PART A
class Person
{
public:
Person();
Person(string pname, int page);
string get_name() const;
int get_age() const;
void set_name(string pname);
void set_age(int page);
private:
string name;
int age; //0 if unknown
};
Person::Person()
{
age = 0;
name = \"\";
}
Person::Person(string pname, int page)
{
name = pname;
age = page;
}
string Person::get_name() const
{
return name;
}
int Person::get_age() const
{
return age;
}
void Person::set_name(string pname)
{
name = pname;
}
void Person::set_age(int page)
{
age = page;
}
void printVector(vector<int> V)
{
vector<int>::iterator it;
for(it=V.begin() ; it < V.end(); it++)
cout<<*it<<\" \";
cout<<endl;
}
int main()
{
srand(time(NULL));
int len_vector = 10; //length of the vector
int RAND_RANGE = 100;
int i, r;
vector<int> V;
//PART B
for(i=0;i<len_vector;i++)
{
r = rand()%RAND_RANGE+1;
V.push_back(r);
}
printVector(V);
V.clear();
//PART C
for(i=0;i<len_vector;i++)
{
r = rand()%RAND_RANGE+1;
if ( find(V.begin(), V.end(), r) == V.end() )
V.push_back(r);
else
i--;
}
printVector(V);
return 1;
}


