I’m writing a program where the user inputs names and then ages. The program then sorts the list alphabetically and outputs the pairs. However, I’m not sure how to keep the ages matched up with the names after sorting them alphabetically. All I’ve got so far is…
Edit: Changed the code to this –
#include "std_lib_facilities.h"
struct People{
string name;
int age;
};
int main()
{
vector<People>nameage;
cout << "Enter name then age until done. Press enter, 0, enter to continue.:\n";
People name;
People age;
while(name != "0"){
cin >> name;
nameage.push_back(name);
cin >> age;
nameage.push_back(age);}
vector<People>::iterator i = (nameage.end()-1);
nameage.erase(i);
}
I get compiler errors for the != operator and the cin operators. Not sure what to do.
Rather than two vectors (one for names, and one for ages), have a vector of a new type that contains both:
edit for comments:
Keep in mind what you’re now pushing onto the vector. You must push something of type Person. You can do this in a couple of ways:
Push back a default constructed person and then set the name and age fields:
Give Person a constructor that takes a name and an age, and push a Person with some values:
Create a Person, give it some values, and push that into the vector:
Or more simply:
(thanks avakar)