Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <sstream> //для потоков
- #include <string>
- #include <vector>
- #include <array>
- #include <fstream> // для файла
- #include <cstdlib> // для использования exit()
- using namespace std;
- class InputData
- {
- public:
- enum Discipline // перечесление для предметов
- {
- MATH,
- PHYS,
- INFO,
- MAX_ELEMENT
- };
- struct NAD // структура для массива данных
- {
- string name;
- array<int,MAX_ELEMENT> array;
- };
- private:
- vector<NAD> m_vector;
- public:
- InputData(string fileName) // большой конструктор с реализацей чтения данных из файла
- {
- ifstream inf(fileName);
- if (!inf) // если файл не открывается
- {
- // То выводим следующее сообщение об ошибке и выполняем exit()
- cerr << "Uh oh, SomeText.txt could not be opened for reading!" << endl;
- exit(1);
- }
- int noe ; // number of elements
- inf >> noe;
- m_vector.resize(noe);
- for(int i = 0; i < noe; ++i)
- {
- string tempName;
- for(int a = 0; a < 3; ++a)
- {
- inf >> tempName;
- m_vector[i].name += tempName += " ";
- }
- for(int b = 0; b < MAX_ELEMENT; ++b)
- {
- inf >> m_vector[i].array[b];
- }
- }
- }
- NAD & operator[](const int index);
- double getAverageOfOneStudent(int index) // возвращает среднее оценку трех предметов студента
- {
- return (m_vector[index].array[MATH] + m_vector[index].array[PHYS] + m_vector[index].array[INFO]) / 3.0;
- }
- void printOSOAS(int index = -1) // printOSOAS - print One Student Or All Student. Метод выводит всех студентов ,если параметры не были указаны или одного студента , если был указан его индекс.
- {
- if(index == -1)
- {
- cout << "Количество студентов : " << m_vector.size() << "\n";
- for(int i = 0; i < m_vector.size(); ++i)
- {
- cout << i << " - " << m_vector[i].name;
- for(int b = 0; b < MAX_ELEMENT; ++b)
- {
- cout << m_vector[i].array[b] << " ";
- }
- cout << "\n";
- }
- }
- else
- {
- cout << m_vector[index].name;
- for(int i = 0; i < MAX_ELEMENT; ++i)
- {
- cout << m_vector[index].array[i];
- }
- }
- }
- int getAmountOfStudents() // возращает общее количество студентов
- {
- return m_vector.size();
- }
- void sortStudent() // сортировку я взял с урока 77 и модифицировал
- {
- // Перебираем каждый элемент массива
- // (кроме последнего, он уже будет отсортирован к тому времени, когда мы до него доберёмся)
- for (int startIndex = 0; startIndex < getAmountOfStudents() - 1; ++startIndex)
- {
- // В переменной smallestIndex хранится индекс наименьшего значения, которое мы нашли в этой итерации
- // Начинаем с того, что наименьший элемент в этой итерации - это первый элемент (индекс 0)
- int smallestIndex = startIndex;
- // Затем ищем элемент поменьше в остальной части массива
- for (int currentIndex = startIndex + 1; currentIndex < getAmountOfStudents(); ++currentIndex)
- {
- // Если мы нашли элемент, который меньше нашего наименьшего элемента,
- if (getAverageOfOneStudent(currentIndex) <= getAverageOfOneStudent(smallestIndex))
- // то запоминаем его
- smallestIndex = currentIndex;
- }
- // smallestIndex теперь наименьший элемент
- // Меняем местами наше начальное наименьшее число с тем, которое мы обнаружили
- std::swap(m_vector[startIndex], m_vector[smallestIndex]);
- }
- }
- int getSRD(int index, Discipline type) //getSRD - get Student Rating Discipline. Возращает оценку по предмету студента
- {
- return m_vector[index].array[type];
- }
- string & getName(int index) // возращает имя студента
- {
- return m_vector[index].name;
- }
- };
- InputData::NAD & InputData::operator[](const int index) //перезагрузка оператора [] для последуещего доступа к элументам через структуру NAD(имеет доступ public)
- {
- return m_vector[index];
- }
- int main()
- {
- setlocale(LC_ALL, "Russian");
- InputData input("input_data.txt");
- input.printOSOAS();
- input.sortStudent();
- input.printOSOAS();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement