Вы находитесь на странице: 1из 10

Министерство образования республики Молдова

Технический университет Молдовы


Факультет Вычислительной техники, Информатики и
Микроэлектроники

Отчёт
по лабораторной работе №1
по ООП

Выполнил cтудент гр. SI-182 : Кравец В.

Проверил: Митителу В.

Кишинёв 2019
Структура – механизм абстракции

Цели работы:
 изучение основ абстракции;
 изучение правил определения и использования структур данных;
 создание переменных типа структуры, обращение к полям;
 изучение принципов программирования, основанных на работе со структурами.

Задание :

а) Создать абстрактный тип данных (структура) - книга, у которой есть название,


автор, издательство, объем в страницах и год издания. Определить функции
установки, изменения данных, сравнения. Для задания текстовых полей
использовать оператор new. Освободить память. В main-е, привести пример
поиска нужной книги по названию и по автору.
b) Создать абстрактный тип данных (структура) - вектор, который имеет
указатель на short и число элементов. Определить функции: инициализации,
удаления вектора, установки/ изменения размера, доступа к элементам вектора,
вычисления суммы четных элементов вектора. Для примера, в функции main,
организовать сравнение векторов.

Исходный код :
//Пункт А
#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
//8 вариант
struct book
{
char *name;
char *author;
char *publishing;
int vol;
int year;
};

void setValues (book &p, char *nm, char *auth, char *publ, int vlm, int yr)
{
p.name = new char[strlen(nm)+1];
strcpy(p.name,nm);
p.author = new char[strlen(auth)+1];
strcpy(p.author,auth);
p.publishing = new char[strlen(publ)+1];
strcpy(p.publishing,publ);
p.vol = vlm;
p.year = yr;
}

void show (book p)


{
cout<<p.name<<", "<<p.author<<", "<<p.publishing<<", "<<p.vol<<",
"<<p.year<<endl;
}

void sort(book *p, int n)


{
book temp;
bool changed;
do
{
changed = false;
for(int i=0;i<n-1;i++)
{
if(p[i].vol > p[i+1].vol)
{
changed = true;
temp = p[i];
p[i] = p[i+1];
p[i+1]=temp;
}
}
}
while (changed);
}

void showAll (book *p, int n)


{
for (int i=0; i<n; i++)
show(p[i]);
}

void freeMem (book *p, int n)


{
for (int i = 0; i < n; i++)
{
delete[] p;
}
}

int main(int argc, char const *argv[])


{
int n=0;
book *p;
cout<<"Enter a number of books "<<endl;
cin>>n;
p = new book[n];
char nm[80], auth[50], publ[15];
int vlm, yr;

for (int i=0; i<n; i++)


{
cout<<"Book's number: "<<i+1<<endl;
cout<<"Enter a name of the book: ";
cin>>nm;
cout<<"Enter an author's name: ";
cin>>auth;
cout<<"Enter a name of the publishing house: ";
cin>>publ;
cout<<"Enter a volume of the book: ";
cin>>vlm;
cout<<"Enter a year of publication: ";
cin>>yr;
setValues(p[i],nm,auth,publ,vlm,yr);
}
cout<<"The initial list of books: "<<endl;
showAll(p,n);

sort(p,n);
cout<<"The list of the books after sorting (by volume): "<<endl;
showAll(p,n);
char *a, *b;
cout<<"Enter a name of a book: ";
cin>>a;
putchar('\n');
cout<<"Enter an author's name: ";
cin>>b;
int x1,x2;
putchar('\n');
bool mark = false;
for (int i=0; i<n; i++)
{
// cout<<a<<'='<<p[i].name<<endl<<b<<"="<<p[i].author<<endl;
x1 = strcmp(a,p[i].name);
x2 = strcmp(b,p[i].author);
if (x1+x2==0)
{
cout<<"There is the book"<<endl;
cout<<p[i].name<<", "<<p[i].author<<", "<<p[i].publishing<<",
"<<p[i].vol<<", "<<p[i].year<<endl;
mark = true;
}
}
if (mark == false)
cout<<"There is no book"<<endl;
// search(p,n,a,b);
putchar('\n');
// freeMem(p,n);
// showAll(p,n);
return 0;

//Пункт Б
#include <iostream>
#include <algorithm>
using namespace std;
struct vector
{
int *a;
int n;
};

void init(vector *v, int n)


{
v->n=n;
v->a=new int[n];
}

void del(vector *v)


{
delete[] v->a;
v->n=0;
}

void change_size(vector *v, int n)


{
v->n=n;
v->a=new int[n];
}

int access (vector *v, int i)


{
return v->a[i];
}

int evenSum (vector *v)


{
int sum=0;
for (int i=0; i<v->n; i++)
{
if (v->a[i]%2==0)
sum+=v->a[i];
}
return sum;
}

int main()
{
vector v;
int t,k,p;
bool cmp=false;
int option;
choice:
cout<<"1. Initialize the vector\n2. Delete the vector\n3. Change the size of the
vector\n4. Access a vector element\n5. Calculate the sum of the vector elements\n6.
Compare two vectors\n7. Exit\n";
while(1)
{
cin>>option;
switch (option)
{
case 1:
init(&v,5);
cout<<"Enter the vector elements"<<endl;
for(int i=0; i<5; i++)
{
cin>>v.a[i];
}
goto choice;
break;
case 2:
del(&v);
goto choice;
break;
case 3:
cout<<"Enter a new vector size"<<endl;
cin>>t;
change_size(&v,t);
cout<<"Enter the new vector elements"<<endl;
for(int i=0; i<t; i++)
{
cin>>v.a[i];
}
goto choice;
break;
case 4:
cout<<"Enter the position number of the desired element to access
it"<<endl;
cin>>k;
cout<<access(&v,k-1)<<endl;
goto choice;
break;
case 5:
cout<<"The sum of the even vector elements is "<<evenSum(&v)<<endl;
goto choice;
break;
case 6:
cout<<"Enter a number of elements of an another vector to
compare"<<endl;
cin>>p;
int *m;
m = new int[p];
cout<<"Enter elements of the vector to compare"<<endl;
for(int i=0; i<p; i++)
{
cin>>m[i];
}
for (int i=0; i<p; i++)
{
if (v.n == p)
{
if (v.a[i] != m[i])
{
cmp=true;
cout<<"The vectors are different"<<endl;
break;
}
}
else
{
cmp=true;
cout<<"The vectors are different"<<endl;
break;
}
}
if (cmp==false)
{
cout<<"The vectors are the same"<<endl;
}
goto choice;
break;
case 7:
exit(0);
default:
goto choice;
}
}
return 0;
}
Полученные результаты :

Пункт А
Пункт Б

Вам также может понравиться