Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- struct Person
- {
- uint16_t id;
- char* fname;
- char* sname;
- uint8_t age;
- void init(uint16_t idP, const char* fnameP, const char* snameP, uint8_t ageP)
- {
- id = idP;
- size_t strLen{ strlen(fnameP) + 1 };
- fname = new char[strLen];
- strcpy_s(fname, strLen, fnameP);
- strLen = strlen(snameP) + 1;
- sname = new char[strLen];
- strcpy_s(sname, strLen, snameP);
- age = ageP;
- }
- void print(bool fnameFirst = true)
- {
- std::cout << id << " : " <<
- (fnameFirst ? fname : sname)
- << ' ' <<
- (fnameFirst ? sname :fname)
- << " - " << +age;
- }
- void setFName(const char* fnameP)
- {
- size_t pStrLen{ strlen(fname) + 1 };
- size_t strLen{ strlen(fnameP) + 1 };
- // if memory not limited
- if (pStrLen < strLen)
- {
- delete[] fname;
- fname = new char[strLen];
- }
- strcpy_s(fname, strLen, fnameP);
- }
- void setSName(const char* snameP)
- {
- size_t pStrLen{ strlen(sname) + 1 };
- size_t strLen{ strlen(snameP) + 1 };
- // if memory not limited
- if (pStrLen < strLen)
- {
- delete[] sname;
- sname = new char[strLen];
- }
- strcpy_s(sname, strLen, snameP);
- }
- void input()
- {
- char buf[50];
- std::cout << "Enter id: "; std::cin >> id;
- std::cin.ignore(100, '\n');
- std::cout << "Enter First name: ";
- std::cin.getline(buf, 49);
- setFName(buf);
- std::cout << "Enter Second name: ";
- std::cin.getline(buf, 49);
- setSName(buf);
- int ageP;
- std::cout << "Enter age: "; std::cin >> ageP; age = ageP;
- std::cin.ignore(100, '\n');
- }
- void clear()
- {
- delete[] fname;
- delete[] sname;
- }
- };
- template <typename T>
- void sort(T* arr, int arrSize, bool(*criteria)(const T&, const T&))
- {
- T copy;
- for (int head{ 0 }; head < arrSize; ++head)
- {
- for (int tail{ arrSize - 1 }; tail > head; --tail)
- {
- if (criteria(arr[tail], arr[head]))
- {
- copy = arr[tail];
- arr[tail] = arr[head];
- arr[head] = copy;
- }
- }
- }
- }
- bool personById(const Person& personA, const Person& personB)
- {
- return personA.id < personB.id;
- }
- bool personByAge(const Person& personA, const Person& personB)
- {
- return personA.age < personB.age;
- }
- int main()
- {
- const int peopleCount{ 3 };
- Person people[peopleCount];
- people[0].init(21, "Ivan", "Petrov", 40);
- people[1].init(2, "Sidor", "Ivanov", 19);
- people[2].init(32, "Petr", "Sidorov", 33);
- for (int i{ 0 }; i < peopleCount; ++i)
- {
- people[i].print(); std::cout << '\n';
- }
- std::cout << "Sort by preson id:\n";
- sort(people, peopleCount, personById);
- for (int i{ 0 }; i < peopleCount; ++i)
- {
- people[i].print(); std::cout << '\n';
- }
- std::cout << "Sort by preson age:\n";
- sort(people, peopleCount, personByAge);
- for (int i{ 0 }; i < peopleCount; ++i)
- {
- people[i].print(); std::cout << '\n';
- }
- for (int i{ 0 }; i < peopleCount; ++i)
- {
- people[i].clear();
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement