# Урок 2 зачем мучаться

Jun 10th, 2023
667
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. #include <algorithm>
2. #include <iostream>
3. #include <string>
4. #include <vector>
5.
6. using namespace std;
7.
8. enum class Gender { FEMALE, MALE };
9.
10. struct Person {
11.     int age;           // возраст
12.     Gender gender;     // пол
13.     bool is_employed;  // имеет ли работу
14. };
15.
16. template <typename InputIt>
17. int ComputeMedianAge(InputIt range_begin, InputIt range_end) {
18.     if (range_begin == range_end) {
19.         return 0;
20.     }
21.     vector<typename InputIt::value_type> range_copy(range_begin, range_end);
22.     auto middle = range_copy.begin() + range_copy.size() / 2;
23.     nth_element(range_copy.begin(), middle, range_copy.end(), [](const Person& lhs, const Person& rhs) {
24.         return lhs.age < rhs.age;
25.     });
26.     return middle->age;
27. }
28.
29. // напишите сигнатуру и реализацию функции PrintStats
30. void PrintStats(vector<Person>& persons) {
31.     cout << "Median age = "s << ComputeMedianAge(persons.begin(), persons.end()) << endl;
32.     auto it = partition(persons.begin(), persons.end(), [](Person& person) {return person.gender == Gender::FEMALE; });
33.     cout << "Median age for females = "s << ComputeMedianAge(persons.begin(), it) << endl;
34.     it = partition(persons.begin(), persons.end(), [](Person& person) {return person.gender == Gender::MALE; });
35.     cout << "Median age for males = "s << ComputeMedianAge(persons.begin(), it) << endl;
36.     it = partition(persons.begin(), persons.end(), [](Person& person) {return person.gender == Gender::FEMALE && person.is_employed; });
37.     cout << "Median age for employed females = "s << ComputeMedianAge(persons.begin(), it) << endl;
38.     it = partition(persons.begin(), persons.end(), [](Person& person) {return person.gender == Gender::FEMALE && !person.is_employed; });
39.     cout << "Median age for unemployed females = "s << ComputeMedianAge(persons.begin(), it) << endl;
40.     it = partition(persons.begin(), persons.end(), [](Person& person) {return person.gender == Gender::MALE && person.is_employed; });
41.     cout << "Median age for employed males = " << ComputeMedianAge(persons.begin(), it) << endl;
42.     it = partition(persons.begin(), persons.end(), [](Person& person) {return person.gender == Gender::MALE && !person.is_employed; });
43.     cout << "Median age for unemployed males = "s << ComputeMedianAge(persons.begin(), it) << endl;
44. }
45.
46. int main() {
47.     vector<Person> persons = {
48.         {31, Gender::MALE, false},   {40, Gender::FEMALE, true},  {24, Gender::MALE, true},
49.         {20, Gender::FEMALE, true},  {80, Gender::FEMALE, false}, {78, Gender::MALE, false},
50.         {10, Gender::FEMALE, false}, {55, Gender::MALE, true},
51.     };
52.     PrintStats(persons);
53. }