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;
}
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;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.