1

Задание: Исходная последовательность содержит сведения об абитуриентах. Каждый элемент последовательности включает следующие поля: <Год поступления> <Номер школы> <Фамилия> Определить, в какие годы общее число абитуриентов для всех школ было наибольшим, и вывести это число, а также количество таких лет. Каждое число выводить на новой строке. Указание. Выполните группировку по полю «год», сохранив

полученную последовательность во вспомогательном отображении. Используя алгоритм max_element, найдите наибольшее число абитуриентов, после чего воспользуйтесь алгоритмом count_if, чтобы определить количество лет, для которых число абитуриентов было максимальным.

Написал кусок кода: клас с полями (<Год поступления> <Номер школы> <Фамилия>), ввод информации с консоли в list

Кто может помочь заранее спасибо!


#include <string>
#include <fstream>
#include <iostream>
#include <list>
#include <set>  // заголовочный файл множеств и мультимножеств
#include <iterator>
using namespace std;
class MyRec
{
    string fname, name;
    int year;
public:
    MyRec() {};
    string GetName() const { return name; };
    void SetName(string n) { name = n; }
    string GetFName() const { return fname; };
    void SetFName(string n) { fname = n; }
    int GetYear() const { return year; };
    void SetYear(int n) { year = n; }
    bool operator < (MyRec s)
    {
        return year < s.year;
    }
};
int main(int argc, char* argv[])
{
    cout << "Hello !!! Testing list \n" << endl;
    string yes = "Y";
    list<MyRec> mylist;
    do
    {
        MyRec temp;
        string fn, n;
        int y;
        cout << " Input fname "; cin >> fn; temp.SetFName(fn);
        cout << " Input name "; cin >> n; temp.SetName(n);
        cout << " Input year "; cin >> y; temp.SetYear(y);
        mylist.push_back(temp);
        cout << " If you want input press Y/N \n";
            cin >> yes;
    } while (yes == "Y");


    list<MyRec>::iterator mIter;
    mIter = mylist.begin();
    cout << endl;
    while (mIter != mylist.end())
    {
        MyRec temp;
        temp = *mIter;
        cout << " Fname =" << temp.GetFName() << "\t";
        cout << " Name =" << temp.GetName() << "\t";
        cout << " Year =" << temp.GetYear() << "\n";
        mIter++;
    }

    
    return 0;
}
0

1 ответ 1

2

Я решил, может кому пригодиться)

#include <string>
#include <iostream>
#include <set>  // заголовочный файл множеств и мультимножеств
#include <iterator>
#include <vector>
#include <map>
#include <algorithm>
#include <Windows.h>

using namespace std;
class MyRec
{
    string lastname;
    int year,schoolNumber;
public:
    MyRec() { lastname = ""; year = 0; schoolNumber = 0; };
    int GetSchoolNumber() const { return schoolNumber; };
    void SetSchoolNumber(int n) { schoolNumber = n; }
    string GetLName() const { return lastname; };
    void SetLName(string n) { lastname = n; }
    int GetYear() const { return year; };
    void SetYear(int n) { year = n; }
};
int maxYear=0;

bool predicate(int n) {
    return (n == maxYear);
}

int main(int argc, char* argv[])
{
    SetConsoleCP(1251);
    SetConsoleOutputCP(1251);

    multiset <int> temp;
    multiset<int>::iterator seconditer = temp.begin();
    map<int, int> ar;
    map<int, int>::iterator iter = ar.begin();
    vector<MyRec> myvector;
    string yes = "Y";
    
    do
    {
        MyRec temp;
        string fn;
        int y,n;
        cout << " Введіть прізвище студента "; cin >> fn; temp.SetLName(fn);
        cout << " Введіть номер школи "; cin >> n; temp.SetSchoolNumber(n);
        cout << " Введіть рік "; cin >> y; temp.SetYear(y);
        myvector.push_back(temp);
        cout << " Якщо бажаєте продовжити/закінчити вводити інформацію введіть Y/N \n";
            cin >> yes;
    } while (yes == "Y");

    for (int i = 0; i < myvector.size(); i++) 
    {   
        ar.insert(make_pair(myvector[i].GetYear(), 0));     //Вектор -> map (рік,кількість студентів)
    }

    for (int i = 0; i < myvector.size(); i++)
    {
        iter = ar.begin();
        while (iter != ar.end()) 
        {
            if (myvector[i].GetYear() == iter->first)       //Рахуємо кількість студентів за роками
                iter->second++;
            iter++;
        };
            
    }

    for (iter = ar.begin(); iter != ar.end(); iter++)
    {
        temp.insert(iter->second);
    }

    seconditer = max_element(temp.begin(), temp.end());
    maxYear = *seconditer;
    cout << "Максимальна кількість студентів: "<< maxYear << endl;
    cout << "Кількість таких років:" <<  count_if(temp.begin(), temp.end(), predicate)<< endl;

    return 0;   
}

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.