Using vectors and strings, how do I output name with the lowest age?

I have to write a program in C++, without using a selection sort, that outputs the name you enter with the lowest age. You input 5 names with ages and at the end it outputs the youngest person. This is what I have so far:

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

using namespace std;

int main()
{
vector<int> age;
vector<string> name;
int agein;
string namein;

for(int n = 0; n < 5; n++)
{
cout << "Please input name \n";
cin >> namein;


cout << "Please input age\n";
cin >> agein;


name.push_back(namein);
age.push_back(agein);
}



for()
{

}



return 0;
}



Where it is italicized is where I am stuck. I Know for the second for loop there has to be if statements in it but I am so stuck on what to write next. Any help would be greatly appreciated!

Thank you!
Instead of using a vector try using a map and use the age as the index. Then the youngest should be the first item in the map.

Then create a struct containing both the name and age, so they are together in a single type. Create a single std::map of your struct type.
Last edited on
Its a project that has to include vectors.
You've definitely been told to use vectors? I would still suggest that you keep the name and age in a single type i.e. a struct:

1
2
3
4
5
struct Person
{
   string name;
   int age;
}


Otherwise when you start sorting the names and associated ages will detach. It will be much easier to keep them together as I suggest.

Then you'll just need to iterate through your vector and keep track of the Person instance that has the lowest age. If people[0].age < people[1].age (people is a vector<Person>) then hang onto that Person instance. Then if myperson.age > people[2].age then replace myperson with people[2] etc...
Last edited on
Topic archived. No new replies allowed.