Advertisement
Guest User

Untitled

a guest
Jul 29th, 2019
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 5.30 KB | None | 0 0
  1. #include <iostream>
  2. #include <sstream> //для потоков
  3. #include <string>
  4. #include <vector>
  5. #include <array>
  6. #include <fstream> // для файла
  7. #include <cstdlib> // для использования exit()
  8. using namespace std;
  9.  
  10. class InputData
  11. {
  12. public:
  13.     enum Discipline // перечесление для предметов
  14.     {
  15.         MATH,
  16.         PHYS,
  17.         INFO,
  18.         MAX_ELEMENT
  19.     };
  20.     struct NAD // структура для массива данных
  21.     {
  22.        string name;
  23.        array<int,MAX_ELEMENT> array;
  24.     };
  25. private:
  26.     vector<NAD> m_vector;
  27.  
  28. public:
  29.     InputData(string  fileName) // большой конструктор с реализацей чтения данных из файла
  30.     {
  31.         ifstream inf(fileName);
  32.  
  33.         if (!inf) // если файл не открывается
  34.         {
  35.         // То выводим следующее сообщение об ошибке и выполняем exit()
  36.         cerr << "Uh oh, SomeText.txt could not be opened for reading!" << endl;
  37.         exit(1);
  38.         }
  39.  
  40.         int noe ;  // number of elements
  41.         inf >> noe;
  42.         m_vector.resize(noe);
  43.         for(int i = 0; i < noe; ++i)
  44.         {
  45.         string tempName;
  46.  
  47.         for(int a = 0; a < 3; ++a)
  48.         {
  49.             inf >> tempName;
  50.             m_vector[i].name += tempName += " ";
  51.         }
  52.  
  53.         for(int b = 0; b < MAX_ELEMENT; ++b)
  54.         {
  55.             inf >> m_vector[i].array[b];
  56.         }
  57.  
  58.         }
  59.     }
  60.     NAD & operator[](const int index);
  61.     double getAverageOfOneStudent(int index) // возвращает среднее оценку трех предметов студента
  62.     {
  63.         return (m_vector[index].array[MATH] + m_vector[index].array[PHYS] + m_vector[index].array[INFO]) / 3.0;
  64.     }
  65.     void printOSOAS(int index = -1) // printOSOAS - print One Student Or All Student. Метод выводит всех студентов ,если параметры не были указаны или одного студента , если был указан его индекс.
  66.     {
  67.         if(index == -1)
  68.         {
  69.             cout << "Количество студентов : " << m_vector.size() << "\n";
  70.             for(int i = 0; i < m_vector.size(); ++i)
  71.             {
  72.                 cout << i << " - " << m_vector[i].name;
  73.                 for(int b = 0; b < MAX_ELEMENT; ++b)
  74.                 {
  75.                     cout << m_vector[i].array[b] << " ";
  76.                 }
  77.                 cout << "\n";
  78.             }
  79.         }
  80.         else
  81.         {
  82.             cout << m_vector[index].name;
  83.             for(int i = 0; i < MAX_ELEMENT; ++i)
  84.             {
  85.                 cout << m_vector[index].array[i];
  86.             }
  87.         }
  88.     }
  89.     int getAmountOfStudents() // возращает общее количество студентов
  90.     {
  91.         return m_vector.size();
  92.     }
  93.     void sortStudent() // сортировку я взял с урока 77 и модифицировал
  94.     {
  95.         // Перебираем каждый элемент массива
  96.         // (кроме последнего, он уже будет отсортирован к тому времени, когда мы до него доберёмся)
  97.     for (int startIndex = 0; startIndex < getAmountOfStudents() - 1; ++startIndex)
  98.     {
  99.         // В переменной smallestIndex хранится индекс наименьшего значения, которое мы нашли в этой итерации
  100.         // Начинаем с того, что наименьший элемент в этой итерации - это первый элемент (индекс 0)
  101.         int smallestIndex = startIndex;
  102.  
  103.         // Затем ищем элемент поменьше в остальной части массива
  104.         for (int currentIndex = startIndex + 1; currentIndex < getAmountOfStudents(); ++currentIndex)
  105.         {
  106.             // Если мы нашли элемент, который меньше нашего наименьшего элемента,
  107.             if (getAverageOfOneStudent(currentIndex) <= getAverageOfOneStudent(smallestIndex))
  108.                 // то запоминаем его
  109.                 smallestIndex = currentIndex;
  110.         }
  111.  
  112.         // smallestIndex теперь наименьший элемент
  113.                 // Меняем местами наше начальное наименьшее число с тем, которое мы обнаружили
  114.         std::swap(m_vector[startIndex], m_vector[smallestIndex]);
  115.     }
  116.  
  117.     }
  118.     int getSRD(int index, Discipline type) //getSRD - get Student Rating Discipline. Возращает оценку по предмету студента
  119.     {
  120.         return m_vector[index].array[type];
  121.     }
  122.     string & getName(int index) // возращает имя студента
  123.     {
  124.         return m_vector[index].name;
  125.     }
  126. };
  127.    InputData::NAD & InputData::operator[](const int index) //перезагрузка оператора [] для последуещего доступа к элументам через структуру NAD(имеет доступ public)
  128.    {
  129.        return m_vector[index];
  130.    }
  131. int main()
  132. {
  133.     setlocale(LC_ALL, "Russian");
  134.     InputData input("input_data.txt");
  135.     input.printOSOAS();
  136.     input.sortStudent();
  137.     input.printOSOAS();
  138.  
  139.     return 0;
  140. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement