Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I need help with a coding problem. I will award full points to the first person

ID: 643527 • Letter: I

Question

I need help with a coding problem. I will award full points to the first person whos correct works. I'd appreciate it if you included an explanation so I understand what it is you're doing.

To help you get started:

#include <iostream>
#include <vector>
#include <string>

using namespace std;

void addNames(vector<string>& names)
{
names.push_back("Seppi");
names.push_back("Farrell");
names.push_back("Burton");
}

void print(vector<string> names)
{
for (int i = 0; i < names.size(); i++)
{
cout << names[i] << endl;
}
}
//
//CODE HERE
//
int main()
{
vector<string> names;

addNames(names);

string nameToErase;
cin >> nameToErase;

int indexFound = findName(names, nameToErase);

if (indexFound != -1)
{
cout << indexFound << endl;
}
else
{
cout << "The name is not found." << endl;
}

print(names);

return 0;
}

The program will prompt the user for a value and will try to find it in the populated vector in the main function. The program will call the 'findName' function, which you will write. If the value is in the vector, then erase it, but return the index it was found in. The 'findName' function MUST return -1 if the value is NOT found in the vector. If the value is not in the vector, the main will print, The name is not found. At the end of the program, the vector will be printed out to check if the correct name was deleted or not.

Explanation / Answer

#include <iostream>
#include <vector>
#include <string>

using namespace std;

void addNames(vector<string>& names){
   names.push_back("Seppi");
   names.push_back("Farrell");
   names.push_back("Burton");
}

void print(vector<string> names){
   for (int i = 0; i < names.size(); i++){
       cout << names[i] << endl;
   }
}

int findName(vector<string> &names, string nametoErase){
   int ind = -1;
   for(int i = 0; i < names.size(); ++i){
       if(names[i] == nametoErase){
           names.erase(names.begin() + i);
           ind = i;
           break;
       }
   }
   return ind;
}

int main(){
   vector<string> names;
   addNames(names);
   string nameToErase;
   cin >> nameToErase;
   int indexFound = findName(names, nameToErase);
   if (indexFound != -1){
       cout << indexFound << endl;
   }
   else{
       cout << "The name is not found." << endl;
   }
   print(names);
   return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote