Skip to content

Instantly share code, notes, and snippets.

@Ruthenus
Created August 27, 2025 06:59
Show Gist options
  • Select an option

  • Save Ruthenus/c887e2b42dca7a6096d0d91528f13c90 to your computer and use it in GitHub Desktop.

Select an option

Save Ruthenus/c887e2b42dca7a6096d0d91528f13c90 to your computer and use it in GitHub Desktop.
Week 32 Homework in IT STEP Academy (STL subcourse)
/**
* STANDART TEMPLATE LIBRARY
* Використати контейнер <set>, й відповідний ітератор, для збереження
* об'єктів типу Student. Використати алгоритми STL для пошуку елемента.
*/
#include <string>
#include <iostream>
#include <set>
#include <algorithm>
#include <windows.h>
using namespace::std;
// Клас Student для збереження інформації про студента і студенток
class Student
{
private:
string name; // власне ім'я студента
unsigned short age; // вік студента (для студентки - вигаданий)
string university; // університет
string formOfEducation; // форма навчання
public:
// Конструктор для ініціалізації об'єкта класу Student
Student(string n, unsigned short a, string u, string ef) :
name(n), age(a), university(u), formOfEducation(ef) {
}
// Модифікатори (сеттери) для встановлення значень полів
void SetName(const string& n) { this->name = n; }
void SetAge(unsigned short a) { this->age = a; }
void SetUniversity(const string& u) { this->university = u; }
void SetFormOfEducation(const string& ef) { this->formOfEducation = ef; }
// Інспектори (геттери) для отримання значень полів
string GetName() const { return name; }
unsigned short GetAge() const { return age; }
string GetUniversity() const { return university; }
string GetFormOfEducation() const { return formOfEducation; }
// Оператор порівняння < для впорядкування об'єктів у set.
// Використовується для організації бінарного дерева пошуку в set.
// https://en.cppreference.com/w/cpp/container/set/find
// https://en.cppreference.com/w/cpp/named_req/Compare
bool operator<(const Student& other) const
{
if (GetName() != other.GetName())
return GetName() < other.GetName();
if (GetAge() != other.GetAge())
return GetAge() < other.GetAge();
if (GetUniversity() != other.GetUniversity())
return GetUniversity() < other.GetUniversity();
return GetFormOfEducation() < other.GetFormOfEducation();
}
// Оператор порівняння == для перевірки рівності об'єктів.
// Використовується для алгоритмів пошуку та порівняння
bool operator==(const Student& other) const
{
return
GetName() == other.GetName() &&
GetAge() == other.GetAge() &&
GetUniversity() == other.GetUniversity() &&
GetFormOfEducation() == other.GetFormOfEducation();
}
// Перевантаження оператора виведення для зручного відображення об'єкта
friend ostream& operator<<(ostream& os, const Student& s)
{
return os << s.GetName() << ", " << s.GetAge() << ", "
<< s.GetUniversity() << ", " << s.GetFormOfEducation();
}
};
int main() {
// Налаштування кодування консолі для української мови
SetConsoleOutputCP(1251);
// Створення контейнера <set> для зберігання об'єктів Student
set<Student> students;
// Додавання "студентів" до контейнера <set> за допомогою emplace для
// ефективного конструювання об'єктів напряму в пам'яті контейнера.
// https://en.cppreference.com/w/cpp/container/set/emplace
// https://en.cppreference.com/w/cpp/container/set/insert
// insert може викликати копіювання або переміщення об'єкта.
students.emplace(Student("Руслан", 18, "ОНПУ", "Денна"));
students.emplace(Student("Каріна", 18, "ОДУВС", "Денна"));
students.emplace(Student("Стефанія", 18, "ОЮА", "Денна"));
students.emplace(Student("Ірина", 19, "ОНПУ", "Денна"));
students.emplace(Student("Людмила", 19, "ОНПУ", "Денна"));
students.emplace(Student("Юліана", 21, "ОНУ", "Дистанційна"));
students.emplace(Student("Інесса", 24, "ОНМедУ", "Інтернатура"));
students.emplace(Student("Тетяна", 25, "ОНЕУ", "Вечірня"));
students.emplace(Student("Світлана", 26, "ОЮА", "Заочна"));
students.emplace(Student("Дарина", 27, "ОЮА", "Аспірантура"));
students.emplace(Student("Ольга", 22, "ОНАХТ", "Денна"));
students.emplace(Student("Роксолана", 22, "ОЮА", "Вечірня"));
students.emplace(Student("Надія", 29, "ОЮА", "Вечірня"));
students.emplace(Student("Анастасія", 27, "ОНПУ", "Денна"));
students.emplace(Student("Любов", 28, "ТНЕУ", "Заочна"));
students.emplace(Student("Надія", 29, "ЛНУ", "Заочна"));
students.emplace(Student("Любов", 30, "ОНМедУ", "Заочна"));
students.emplace(Student("Юлія", 32, "ОНУ", "Дистанційна"));
students.emplace(Student("Зоряна", 25, "ТНПУ", "Дистанційна"));
students.emplace(Student("Юлія", 30, "ОЮА", "Денна"));
// і тим подібні
students.emplace(Student("Руслан", 38, "IT STEP", "Напівстаціонар"));
// Пошук фатальної студентки за допомогою методу find
// https://en.cppreference.com/w/cpp/container/set/find
auto iterator = students.find(Student("Ольга", 22, "ОНАХТ", "Денна"));
if (iterator != students.end()) {
cout << "Знайдено методом find: " << *iterator << ".\n";
}
// Алгоритм find використовує бінарний пошук у впорядкованому set.
// Повертає ітератор на знайдений елемент або students.end(), якщо
// елемент відсутній.
// Пошук діапазону студентів з однаковими значеннями ("пошук себе").
// Алгоритм методу equal_range повертає пару ітераторів: нижню (перший
// елемент >= шуканого) та верхню межу (перший елемент > шуканого).
// https://en.cppreference.com/w/cpp/container/set/equal_range
auto range = students.equal_range(Student("Руслан", 18, "ОНПУ", "Денна"));
if (range.first != students.end()) {
cout << "Нижня межа (lower-bound): " << *range.first << "\n";
}
if (range.second != students.end()) {
cout << "Верхня межа (upper-bound): " << *range.second << "\n";
}
// Виводить у консоль: "...Руслан, 38, IT STEP, Напівстаціонар".
// Перевірка наявності студентського життя за допомогою count.
// Повертає 1, якщо елемент знайдено, або 0, якщо відсутній.
// https://en.cppreference.com/w/cpp/container/set/count
if (students.count(Student("Любов", 28, "ТНЕУ", "Заочна")) != 0 &&
students.count(Student("Любов", 30, "ОНМедУ", "Заочна")) == 1) {
cout << "Любов існує.\n";
}
// Пошук верхньої межі за допомогою upper_bound.
// Повертає ітератор на перший елемент, який строго більший за заданий.
// https://en.cppreference.com/w/cpp/container/set/upper_bound
auto ub = students.upper_bound((Student("Каріна", 18, "ОДУВС", "Денна")));
if (ub != students.end()) {
cout << "upper_bound НЕ про день св. Валентина 1998: " << *ub << ".\n";
}
// Підрахунок студенток Юридичної Академії за допомогою count_if.
// Алгоритм count_if підраховує елементи, для яких виконується критерій.
// https://en.cppreference.com/w/cpp/algorithm/count.html
size_t jurisprudence = count_if(students.begin(), students.end(),
[](const Student& s) { return s.GetUniversity() == "ОЮА"; }
);
cout << "Кількість студенток ОЮА: " << jurisprudence << "!\n";
// Перевірка any_of наявності студенток з певною формою навчання.
// Алгоритм повертає true, якщо хоча б один елемент задовольняє умову.
// https://en.cppreference.com/w/cpp/algorithm/any_of.html
bool hasIntern =
any_of(students.begin(), students.end(), [](const Student& s)
{ return s.GetFormOfEducation() == "Інтернатура"; });
cout << "Були лікарки-інтерни? " << (hasIntern ? "Так" : "Ні") << "\n";
// Перевірка, чи всі студенти повнолітні, за допомогою all_of.
// Алгоритм повертає true, якщо всі елементи задовольняють умову.
// https://en.cppreference.com/w/cpp/algorithm/all_of.html
bool everyoneAdult =
all_of(students.begin(), students.end(), [](const Student& s)
{ return s.GetAge() >= 18; });
cout << "Чи всі повнолітні? " << (everyoneAdult ? "Так" : "Ні") << "\n";
// Пошук студентки за алгоритмом, який їй пасує)))
// https://en.cppreference.com/w/cpp/algorithm/binary_search.html
bool exists = binary_search(students.begin(), students.end(),
Student("Юлія", 32, "ОНУ", "Дистанційна"));
cout << "binary_search: " << (exists ? "є така\n" : "не знайшов!!!\n");
// Перевірка відсутності студентів з дистанційною формою навчання
// за допомогою none_of (радше, присутності таких студенток).
// https://en.cppreference.com/w/cpp/algorithm/none_of.html
bool noWeb =
none_of(students.begin(), students.end(), [](const Student& s)
{ return s.GetFormOfEducation() == "Дистанційна"; });
cout << "Чи немає студентів з дистанційною формою навчання? "
<< (noWeb ? "Так" : "Ні") << "...\n";
// Повертає true, якщо жоден елемент не задовольняє умову.
// Пошук першої студентки, яка не навчалася в ОНПУ, за допомогою
// find_if_not (за допомогою соціальної мережі vkontakte).
// Повертає ітератор на перший елемент, який НЕ задовольняє умову.
// https://en.cppreference.com/w/cpp/algorithm/find.html
auto it =
find_if_not(students.begin(), students.end(), [](const Student& s)
{ return s.GetUniversity() == "ОНПУ" && s.GetName() != "Руслан"; });
if (it != students.end()) {
cout << "Перша студентка не-OНПУ: " << *it << ".\n";
}
// Пошук студента з університету IT STEP за допомогою find_if.
// https://en.cppreference.com/w/cpp/algorithm/find.html
auto it_if = find_if(students.begin(), students.end(),
[](const Student& s) { return s.GetUniversity() == "IT STEP"; });
if (it_if != students.end())
cout << "find_if: знайдено студента Комп'ютерної Академії \"ШАГ\" >> "
<< *it_if << "\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment