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

My teacher commented that \"the part where you find the longest string in the ve

ID: 3918675 • Letter: M

Question

My teacher commented that "the part where you find the longest string in the vector, it's supposed to work correctly for any size vector, so you can't assume it'll only have two elements." He said I am supposed to use a vector loop. The part he was referring to I put in a bold statement. How do I fix it?

#include <iostream>
#include <string>
#include <vector>
using namespace std;

void print(const string* ps)
{
int len = (*ps).size();
cout << len <<endl;
cout<<"Contents of ps:"<<(*ps)<<endl;
}

int main()
{
vector<string> vs;
cout << "Size: " << vs.size() << " Capacity: " << vs.capacity() << endl;

string s1 = "Mike", s2 = "John";

vs.push_back(s1);
vs.push_back(s2);
cout << "Size: " << vs.size() << " Capacity: " << vs.capacity() << endl;

string *ps = NULL;
for(int i = 0; i < vs.size(); i++)
{
ps = &vs[i];
cout << "Contents of ps:" << (*ps) << endl;
}

if(vs.at(0).length() >= vs.at(1).length())
ps = &vs[0];

else
ps = &vs[1];

print(ps);
delete ps;

return 0;
}

Explanation / Answer

#include #include #include using namespace std; void print(const string* ps) { int len = (*ps).size(); cout