Untitled

 avatar
unknown
c_cpp
a year ago
2.4 kB
11
Indexable
#include <bits/stdc++.h>

using namespace std;

class Person{
private:
    string name;
    int age;
    int numHobbies;
    string *hobbies;

public:
    //constructor
    Person(string _name, int _age, int _numHobbies, string *_hobbies)
	:name(_name), age(_age), numHobbies(_numHobbies){
	hobbies = new string[_numHobbies];
	for(int i = 0; i < _numHobbies; ++i){
	    hobbies[i] = _hobbies[i];
	}
    }
    //default constructor
    Person(){
    }
    //copy constructor
    Person(const Person& original)
	:name(original.name), age(original.age), numHobbies(original.numHobbies){
	hobbies = new string[original.numHobbies];
	for(int i = 0; i < original.numHobbies; ++i){
	    hobbies[i] = original.hobbies[i];
	}
    }
    //copy assignment operator
    Person& operator=(const Person& original){
	name = original.name;
	age = original.age;
	numHobbies = original.numHobbies;
	hobbies = new string[original.numHobbies];
	for(int i = 0; i < original.numHobbies; ++i){
	    hobbies[i] = original.hobbies[i];
	}
	return *this;
	
    }

    ~Person(){
	delete[] hobbies;
    }


    void displayInfo(){
	cout << "Name: " << name << ", Age: " << age << ", Number of Hobbies: " << numHobbies << '\n';
	cout << "Hobbies: ";
	for(int i = 0; i < numHobbies; ++i){
	    if(i == 0){
		cout << hobbies[i];
	    }else{
		cout << ", " << hobbies[i];
	    }
	}
	cout << '\n';
    }

    string getName(){
	return name;
    }

    int getAge(){
	return age;
    }

    int getnumHobbies(){
	return numHobbies;
    }

};

bool cmp1(Person p1, Person p2){
    if(p1.getnumHobbies() != p2.getnumHobbies()){
	return p1.getnumHobbies() > p2.getnumHobbies();
    }else if(p1.getAge() != p2.getAge()){
	return p1.getAge() > p2.getAge();
    }
    return p1.getName() < p2.getName();
}

int main()
{
    int n;
    cin >> n;
    vector<Person> persons(n);
    for (int i = 0; i < n; ++i)
    {
	string name;
	int age, numHobbies;
	cin >> name >> age >> numHobbies;
	string *hobbies = new string[numHobbies];
	for (int j = 0; j < numHobbies; ++j)
	{
	    cin >> hobbies[j];
	}
	Person temp(name, age, numHobbies, hobbies);
	persons[i] = temp;
	delete[] hobbies;
    }
    sort(persons.begin(), persons.end(), cmp1);
    for (int i = 0; i < n; ++i)
    {
	cout << "Person " << i + 1 << " info:" << endl;
	persons[i].displayInfo();
    }
    return 0;
}
Editor is loading...
Leave a Comment