Modify the program to prevent duplicate names being inserted in the vector. Modi
ID: 3717742 • Letter: M
Question
Modify the program to prevent duplicate names being inserted in the vector.
Modify the program to prompt the user for another name if best friend is not found.
#include <iostream>
#include <iomanip> // for setw
#include <fstream> // for ifstream
#include <string>
#include <vector>
#include "Person.h"
using namespace std;
main()
{
string name;
vector<Person *> people;
Person * person_pointer;
ifstream in;
in.open("names");
if (!in.is_open()) {
cout<<"Couldn't open 'names' file. ";
return 1;
}
in>>name;
while (!in.eof()) {
person_pointer = new Person(name);
people.push_back(person_pointer);
in>>name;
}
in.close();
int i, j;
for(i=0; i< people.size(); i++) {
cout<< "Who is " << people[i]->get_name() << "'s best friend? ";
cin>>name;
for(j=0; j< people.size(); j++)
if (people[j]->get_name() == name)
break;
if(j < people.size())
people[i]->set_best_friend(people[j]);
else
cout<< "Couldn't find best friend " << name << endl;
}
for (i=0; i<people.size(); i++)
delete people[i];
}
Explanation / Answer
#include <iostream>
#include <iomanip> // for setw
#include <fstream> // for ifstream
#include <string>
#include <vector>
#include "Person.h"
using namespace std;
// check if name is already present in people vector
bool ifAlreadyPresent(vector<Person *> people , string name)
{
int i;
for( i = 0 ; i < people.size() ; i++ )
// getName() returns the name of the person
// change the name of the function accordingly
// if the current person is found
if( people[i].getName() == name )
return true;
return false;
}
main()
{
string name;
vector<Person *> people;
Person * person_pointer;
ifstream in;
in.open("names");
if (!in.is_open()) {
cout<<"Couldn't open 'names' file. ";
return 1;
}
in>>name;
while (!in.eof()) {
person_pointer = new Person(name);
// if the current name is not already present in people vector
if( !ifAlreadyPresent(person_pointer , name) )
people.push_back(person_pointer);
in>>name;
}
in.close();
int i, j;
for(i=0; i< people.size(); i++) {
cout<< "Who is " << people[i]->get_name() << "'s best friend? ";
cin>>name;
for(j=0; j< people.size(); j++)
if (people[j]->get_name() == name)
break;
if(j < people.size())
people[i]->set_best_friend(people[j]);
else
cout<< "Couldn't find best friend " << name << endl;
}
for (i=0; i<people.size(); i++)
delete people[i];
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.