
lab 4 Zhovtyak
.docxГУАП
КАФЕДРА № 41
ОТЧЕТ ЗАЩИЩЕН С ОЦЕНКОЙ
ПРЕПОДАВАТЕЛЬ
Старший преподаватель |
|
|
|
Д.В. Куртяник |
должность, уч. степень, звание |
|
подпись, дата |
|
инициалы, фамилия |
ОТЧЕТ О ЛАБОРАТОРНОЙ РАБОТЕ ШАБЛОНЫ. КОНТЕЙНЕРЫ STL. |
по курсу: ОСНОВЫ ПРОГРАММИРОВАНИЯ |
РАБОТУ ВЫПОЛНИЛ
СТУДЕНТ ГР. № |
4016 |
|
28.05.2021 |
|
М.О.Жовтяк |
|
|
|
подпись, дата |
|
инициалы, фамилия |
Санкт-Петербург 2021
Вариант 17
Цель лабораторной работы: изучение видов контейнеров библиотеки STL, способов их применения и особенностей работы; изучение способов использования шаблонов функций; получение навыков программирования на языке C++.
Задание на программирование: разработать программу и провести анализ быстродействия различных контейнеров.
Мой индивидуальный вариант. Cформировать коллекцию L, включив в неё по одному разу элементы, которые входят в коллекцию L1, но не входят в коллекцию L2.
Алгоритм работы программы: я создам шаблоны, которые заполняют и отображают контейнеры. Далее будут созданы коллекции L1 и L2, которые сразу же будут заполняться. Следующие действия я буду реализовывать, используя методы и алгоритмы STL. После этого коллекция L принимает в себя все значения L1. Сразу же после этого выполняется действие, где L исключает из себя значения, которые могут быть равны элементам L2. Так происходило последовательно с каждым из контейнеров: vector, list, multiset, map.
Для данной задачи подойдут следующий методы и алгоритмы из библиотеки STL:
unique() – для удаление равных соседних элементов при сохранении первого из них;
insert(p, x) – для добавления х перед элементом, на который указывает р;
end() – для указания на элемент, который следует за последним;
begin() – указывает на первый элемент;
find – для нахождения итератора на элемент и проверки на его существование;
count – для возвращения количества элементов с заданным значением;
erase – для удаление конкретного элемента.
remove – удаление элемента с определенным значением
Ответ к задаче:
Согласно выдаче информации программы о выполненном времени каждого контейнера:
Vector – 43 мсек, list – 54 мсек, multiset – 500 мсек, map – 673 мсек;
Для этой задачи оптимальнее всего использовать контейнер vector.
Код программы на С++:
#include <iostream>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <ctime>
#include <algorithm>
#include <ctime>
using namespace std;
//заполение всего, кроме map
template <typename container>
int filling(container &con, int number)
{
int start = clock();
for (int i=0; i<number; i++)
{
int element = rand() % 1001;
con.insert(con.end(), element);
element = 0;
}
int end = clock();
return (end - start);
}
//отображение всего, кроме map
template <typename container>
void showme(container con)
{
cout << "Content of container:";
for (auto i : con)
{
cout << i << " ";
}
cout << endl;
}
//заполнеие map
template <typename Key, typename Valeur>
int filling_m(map<Key, Valeur>& Conteneur, int Longueur)
{
int start = clock();
for (int i = 0; i != Longueur; i++)
{
int ElementNew = rand() % 1001;
int ElementNewKey = i;
auto PaireValeur = make_pair(ElementNewKey, ElementNew);
Conteneur.insert(Conteneur.end(), PaireValeur);
};
int end = clock();
return((end - start));
}
//map
template <typename Key, typename Valeur>
void showme_m(map<Key, Valeur>& Conteneur)
{
cout << "Content of container" << endl;
for (auto elem : Conteneur) { cout << "[" << elem.first << "]=" << elem.second << " "; }
}
int main()
{
cout << "Enter number of values for container" << endl;
int number;
cin >> number;
//vector
cout << "Vector work:" << endl;
vector<int> vect1;
vector<int> vect2;
vector<int> vect;
int time = 0;
time+=filling(vect1, number);
showme(vect1);
cout << "Spent time for now: " << time << endl;
time+=filling(vect2, number);
showme(vect2);
cout << "Spent time for now: " << time << endl;
//создание коллекции L
int start = clock();
vector<int>::iterator it1;
for (it1 = vect1.begin(); it1 != vect1.end(); ++it1)
vect.push_back(*it1);
//сортировка и удаление одинаковых элементов коллекции L для более легкого восприятия
sort(vect.begin(), vect.end());
auto last1 = unique(vect.begin(), vect.end());
vect.erase(last1, vect.end());
//уничтожение элементов L, которые входят в коллекцию L2
for (it1 = vect2.begin(); it1 != vect2.end(); ++it1)
{
vect.erase(remove(vect.begin(), vect.end(), *it1), vect.end());
}
showme(vect);
int end = clock();
time += (end - start);
cout << "Spent time: " << time << endl;
cout << endl;
//обнуление счетчиков времени
time = 0; start = 0; end = 0;
//list
cout << "List work:" << endl;
list<int> lis1;
list<int> lis2;
list<int> lis;
time += filling(lis1, number);
showme(lis1);
cout << "Spent time for now: " << time << endl;
time += filling(lis2, number);
showme(lis2);
cout << "Spent time for now: " << time << endl;
//создание коллекции L
start = clock();
list<int>::const_iterator it2;
it2 = lis1.begin();
while (it2 != lis1.end())
{
lis.push_back(*it2);
it2++;
}
//сортировка и удаление одинаковых элементов коллекции L для более легкого восприятия
lis.sort();
auto last2 = unique(lis.begin(), lis.end());
lis.erase(last2, lis.end());
//уничтожение элементов L, которые входят в коллекцию L2
list<int>::iterator it3;
it3 = lis2.begin();
while(it3 != lis2.end())
{
lis.remove(*it3);
++it3;
}
showme(lis);
end = clock();
time += (end - start);
cout << "Spent time: " << time << endl;
cout << endl;
time = 0; start = 0; end = 0;
//multiset
cout << "Multiset work:" << endl;
multiset<int> mul1;
multiset<int> mul2;
multiset<int> mul;
time += filling(mul1, number);
showme(mul1);
cout << "Spent time for now: " << time << endl;
time += filling(mul2, number);
showme(mul2);
cout << "Spent time for now: " << time << endl;
//создание коллекции L
start = clock();
multiset<int>::const_iterator it4;
it4 = mul1.begin();
while (it4 != mul1.end())
{
mul.insert(*it4);
it4++;
}
//уничтожение элементов L, которые входят в коллекцию L2
multiset<int>::iterator it5;
it5 = mul2.begin();
while (it5 != mul2.end())
{
for (auto it = mul.begin(); it != mul.end(); ) {
if (*it5 == *it)
it = mul.erase(it);
else
++it;
}
++it5;
}
showme(mul);
end = clock();
time += (end - start);
cout << "Spent time: " << time << endl;
cout << endl;
time = 0; start = 0; end = 0;
//map
cout << "Map work:" << endl;
map<int, int> mp1;
map<int, int> mp2;
map<int, int> mp;
time += filling_m(mp1, number);
showme_m(mp1);
cout << endl;
cout << "Spent time for now: " << time << endl;
time += filling_m(mp2, number);
showme_m(mp2);
cout << endl;
cout << "Spent time for now: " << time << endl;
//cоздание коллекции L
start = clock();
map<int, int>::iterator it6;
it6 = mp1.begin();
while (it6 != mp1.end())
{
mp.insert(*it6);
++it6;
}
//уничтожение элементов L, которые входят в коллекцию L2
map<int, int>::iterator it7;
it7 = mp2.begin();
while (it7 != mp2.end())
{
for (auto it = mp.begin(); it != mp.end(); ) {
if (it7->second == it->second)
it = mp.erase(it);
else
++it;
}
++it7;
}
showme_m(mp);
cout << endl;
end = clock();
time += (end - start);
cout << "Spent time: " << time << endl;
}
Скриншот,
наглядно показывающий работу программы
(здесь случайные числа заданы от 0 до 9
для более лёгкого восприятия, изменить
эти значения можно в шаблоне)
Скриншот объективной работы, где произвольные значения находятся в диапазоне от 0 до 1000.
Вывод. Я изучил множество видов контейнеров библиотеки STL, изучил принципы работы шаблонов на С++, параллельно с этим научился применять их на практике. Отточил навыки программирования на С++.