К основному контенту

Коллекции: List, Map, vector, deque. Дуравкина. C++

// 
//Написать функцию, с помощью которой подготовить текстовый файл input.txt сохранив в нею 100 случайных целых чисел в диапазоне 
//от -50 до +50 по одному на строке. Файл возвращается функцией как результат. Написать функцию inputfile(). получающую файл как аргумент
//и возвращающую последовательный контейнер, заполненный числами из файла. Написать функцию modify(), получающую в качестве аргумента 
//контейнер-результат функции inputfile(). Модифицированный контейнер возвращается в качестве результата. Добавить в контейнер-результат 
//вычисление суммы и среднего арифметического по абсолютной величине. 
//В качестве контейнера использовать вектор, двустороннюю очередь и список.
//10. Добавить к каждому числу половину последнего отрицательного числа.


#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <vector>
#include <deque>
#include <list>
#include <iterator>
using namespace std;

ofstream txt()
{
ofstream fout("input.txt"); 
for (int i = 0; i < 100; i++)
fout << rand() % 101 + (-50) << endl; // запись строки в файл
fout.close(); // закрываем файл
return fout;
}
vector<int> inputfile(fstream &file)
{
vector<int> vector_array(100);
ifstream ("input.txt");
for (int i = 0; i < vector_array.size(); i++)
file >> vector_array[i];
return vector_array;
}
deque<int> inputfile_deque(fstream &file)
{
deque<int> deque_array(100);
ifstream("input.txt");
for (int i = 0; i < deque_array.size(); i++)
file >> deque_array[i];
return deque_array;
}
list<int> inputfile_list(fstream &file)
{
list<int> list_array;
ifstream("input.txt");
copy(istream_iterator<int>(file), istream_iterator<int>(), back_inserter(list_array));
return list_array;
}
vector<int> modify (vector<int> arr)
{
int sum = 0;
for (int i = 0; i < 100; i++)
sum += abs(arr[i]);
vector<int> arr_modify(arr);
arr_modify.insert(arr_modify.end(), sum);
arr_modify.insert(arr_modify.end(), sum / 100.0);
int last;
for (int i = arr_modify.size()-1; i > 0; --i)
{
if (arr_modify[i] < 0)
{
last = arr_modify[i];
break;
}
}
for (int i = 0; i < arr_modify.size(); i++)
arr_modify[i] = arr_modify[i] + last/2;
return arr_modify;
}
deque<int> modify_deque (deque<int> arr)
{
int sum = 0;
for (int i = 0; i < 100; i++)
sum += abs(arr[i]);
deque<int> arr_modify(arr);
arr_modify.insert(arr_modify.end(), sum);
arr_modify.insert(arr_modify.end(), sum / 100);
return arr_modify;
}
list<int> modify_list(list<int> arr)
{
int sum = 0;
for (int i = 0; i < 100; i++)
{
list<int>::iterator it = arr.begin();
std::advance(it, i);
int a = *it;
sum += abs(a);
}
list<int> arr_modify(arr);
arr_modify.push_back(sum);
arr_modify.push_back(sum / 100);
return arr_modify;
}

int main()
{
txt();
fstream file("input.txt");
vector<int> arr = inputfile(file);
vector<int> array_modify(modify(arr));
for (int i = 0; i < 102; i++)
cout << array_modify[i] << " ";
cout << endl;
fstream file_deque("input.txt");
deque<int> arr_deque = inputfile_deque(file_deque);
deque<int> array_modify_deque(modify_deque(arr_deque));
for (int i = 0; i < 102; i++)
cout << array_modify_deque[i] << " ";
cout << endl;
fstream file_list("input.txt");
list<int> arr_list = inputfile_list(file_list);
list<int> array_modify_list(modify_list(arr_list));
copy(array_modify_list.begin(), array_modify_list.end(), ostream_iterator<int>(cout, " "));
cout << endl;
return 0;
}

// лаба два.cpp: определяет точку входа для консольного приложения.
//Написать функцию, с помощью которой подготовить текстовый файл input.txt сохранив в нею 100 случайных целых чисел в диапазоне 
//от -50 до +50 по одному на строке. Файл возвращается функцией как результат. Написать функцию inputfile(). получающую файл как аргумент
//и возвращающую последовательный контейнер, заполненный числами из файла. Написать функцию modify(), получающую в качестве аргумента 
//контейнер-результат функции inputfile(). Модифицированный контейнер возвращается в качестве результата. Добавить в контейнер-результат 
//вычисление суммы и среднего арифметического по абсолютной величине. 
//В качестве контейнера использовать вектор, двустороннюю очередь и список.
//10. Добавить к каждому числу половину последнего отрицательного числа.

#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <vector>
#include <deque>
#include <list>
#include <iterator>
using namespace std;

ofstream txt()
{
ofstream fout("input.txt"); 
for (int i = 0; i < 100; i++)
fout << rand() % 101 + (-50) << endl; // запись строки в файл
fout.close(); // закрываем файл
return fout;
}
template <class T>
T<int> inputfile(fstream &file)
{
T<int> vector_array(100);
ifstream ("input.txt");
for (int i = 0; i < vector_array.size(); i++)
file >> vector_array[i];
return vector_array;
}
list<int> inputfile_list(fstream &file)
{
list<int> list_array;
ifstream("input.txt");
copy(istream_iterator<int>(file), istream_iterator<int>(), back_inserter(list_array));
return list_array;
}
template <class T>
T<int> modify (T<int> arr)
{
int sum = 0;
for (int i = 0; i < 100; i++)
sum += abs(arr[i]);
T<int> arr_modify(arr);
arr_modify.insert(arr_modify.end(), sum);
arr_modify.insert(arr_modify.end(), sum / 100.0);
int last;
for (int i = arr_modify.size()-1; i > 0; --i)
{
if (arr_modify[i] < 0)
{
last = arr_modify[i];
break;
}
}
for (int i = 0; i < arr_modify.size(); i++)
arr_modify[i] = arr_modify[i] + last/2;
return arr_modify;
}
list<int> modify_list(list<int> arr)
{
int sum = 0;
for (int i = 0; i < 100; i++)
{
list<int>::iterator it = arr.begin();
std::advance(it, i);
int a = *it;
sum += abs(a);
}
list<int> arr_modify(arr);
arr_modify.push_back(sum);
arr_modify.push_back(sum / 100);
return arr_modify;
}

int main()
{
txt();
fstream file("input.txt");
vector<int> arr = inputfile(file);
vector<int> array_modify(modify(arr));
for (int i = 0; i < 102; i++)
cout << array_modify[i] << " ";
cout << endl;
fstream file_deque("input.txt");
deque<int> arr_deque = inputfile_deque(file_deque);
deque<int> array_modify_deque(modify_deque(arr_deque));
for (int i = 0; i < 102; i++)
cout << array_modify_deque[i] << " ";
cout << endl;
fstream file_list("input.txt");
list<int> arr_list = inputfile_list(file_list);
list<int> array_modify_list(modify_list(arr_list));
copy(array_modify_list.begin(), array_modify_list.end(), ostream_iterator<int>(cout, " "));
cout << endl;
return 0;
}




//Упражнение 3.13. Определить структуру Employee (сотрудник), содер-
//жащую следующие поля : фамилия, имя, должность, зарплата.Разработать
//программу, которая хранит информацию обо всех сотрудниках фирмы в виде
//контейнера типа список.Реализовать :
// • заполнение контейнера данными с клавиатуры;
//• вывод информации о сотрудниках на экран;
//• поиск сотрудников, состоящих на заданной должности;
//• сортировку списка сотрудников по полю фамилия и по полю зарплата.
#include "stdafx.h"
#include <iostream>
#include <list>
#include <string>
#include <iterator>
using namespace std;

struct Employee
{
string soname;
string name;
string position;
int salary;
};
void get(list<Employee> &employee)
{
int flag;
Employee temp;
do
{
cout << "Enter soname: ";
cin >> temp.soname;
cout << endl;
cout << "Enter name: ";
cin >> temp.name;
cout << endl;
cout << "Enter position: ";
cin >> temp.position;
cout << endl;
cout << "Enter salary: ";
cin >> temp.salary;
employee.push_back(temp);
cout << "If you want to continue to introduce staff, press 1, if not - 2" << endl;
cin >> flag;
cout << endl;
} while (flag == 1);
for (int i = 0; i < employee.size(); i++)
{
list<Employee>::iterator it = employee.begin();
std::advance(it, i);
Employee a = *it;
cout << "Soname: " << a.soname << endl << " Name: " << a.name << endl << " Position: "
<< a.position << endl << " Salary: " << a.salary << endl;
}
string pos;
cout << "Enter position: ";
cin >> pos;
for (int i = 0; i < employee.size(); i++)
{
list<Employee>::iterator it = employee.begin();
std::advance(it, i);
Employee a = *it;
if (a.position == pos)
{
cout << "Soname: " << a.soname << endl << " Name: " << a.name << endl << " Salary: " << a.salary << endl;
}
}
bool exit = false; // болевая переменная для выхода из цикла, если массив отсортирован
while (!exit) // пока массив не отсортирован
{
exit = true;
for (int int_counter = 0; int_counter < (employee.size() - 1); int_counter++) 
{
list<Employee>::iterator it = employee.begin();
std::advance(it, int_counter);
Employee a = *it;
list<Employee>::iterator it2 = employee.begin();
std::advance(it2, int_counter+1);
Employee a2 = *it2;
if (a.salary > a2.salary) // сравниваем два соседних элемента
{
temp = a;
a = a2;
a2 = temp;
exit = false; // на очередной итерации была произведена перестановка элементов
}
}
}
for (int i = 0; i < employee.size(); i++)
{
list<Employee>::iterator it = employee.begin();
std::advance(it, i);
Employee a = *it;
cout << "Soname: " << a.soname << endl << " Name: " << a.name << endl << " Position: "
<< a.position << endl << " Salary: " << a.salary << endl;
}
};

void main()
{
list<Employee>employee;
get(employee);
}

//Упражнение 3.14. Разработать программу, которая хранит информацию
//о странах и численности населения в них в виде отображения.Реализовать:
//• заполнение контейнера данными с клавиатуры;
//• вывод информации о странах на экран;
//• поиск информации по заданной стране.
#include "stdafx.h"
#include <iostream>
#include <iterator>
#include <map>
#include <string>
using namespace std;

void main()
{
map <string, int> country;
int flag;
do
{
int p;
string c;
cout << "Enter country and poulation" << endl;
cin >> c >> p;
country.insert(pair<string, int>(c, p));
cout << "If you want to continue to introduce staff, press 1, if not - 2" << endl;
cin >> flag;
cout << endl;
} while (flag == 1);
for (auto it = country.begin(); it != country.end(); ++it)///вывод на экран
{
cout << it->first << " : " << it->second << endl;
}
string c;
cout << "Enter Seeking country" << endl;
cin >> c;
auto itMap = country.find(c);
cout << itMap->first << " : " << itMap->second << endl;
}

//Упражнение 3.15. Разработать программу, которая хранит информацию
//о школьниках и их оценках за 5 экзаменов в виде отображения(map).Каж -
//дый элемент отображения должен иметь следующий вид : ключ – фамилия
//ученика, значение – набор оценок за пять экзаменов.Реализовать вывод на
//экран среднего балла по всем экзаменам для каждого ученика.
#include "stdafx.h"
#include <iostream>
#include <map>
#include <string>
using namespace std;

struct arr
{
int mass[5];
};
typedef map<string, arr> mm;

void display(mm p)
{
for (mm::iterator it = p.begin(); it != p.end(); ++it)
{
int sum = 0;
cout << (*it).first << " : ";
for (int i = 0; i < 5; i++)
{
sum += (*it).second.mass[i];
}
cout << sum / 5.0 << endl;
}
}

int main()
{
mm pupil;
arr  a = { 1, 2, 3, 4, 5 };
pupil["Jack"] = a;
for (int i = 0;i<5;i++)
a.mass[i] = i + 1;
pupil["Order"] = a;
for (int i = 0;i<5;i++)
a.mass[i] = 1;
pupil["Ones"] = a;
display(pupil);
system("pause");
return 0;
}

//Упражнение 3.16.Определить класс autoOwnerDirectory(каталог авто -
//владельцев), хранящий информацию об автовладельцах и номерах их авто -
//мобилей и реализующий следующий набор функций :
//• добавление новой записи в каталог;
//• удаление записи из каталога;
//• редактирование записи в каталоге;
//• поиск фамилии автовладельца по сочетанию цифр и букв в номере авто -
//мобиля;
//• вывод записей каталога, отсортированных по номерам.
//Информацию об автовладельцах и номерах их автомобилей внутри клас -
//са хранить в виде мультиотображения.
//Разработать программу, демонстрирующую работу с созданным классом.
#include "stdafx.h"
#include <iostream>
#include <map>
#include <string>
using namespace std;

class autoOwnerDirectory
{
private:
multimap<string, string> owner;
public:
void add()
{
int flag;
do
{
string name, num;
cout << "Enter owner and number" << endl;
cin >> name >> num;
owner.insert(pair<string, string>(name, num));
cout << "If you want to continue to introduce owner, press 1, if not - 2" << endl;
cin >> flag;
cout << endl;
} while (flag == 1);
}
void del()
{
string temp;
cout << "Enter deleted owner" << endl;
cin >> temp;
auto itMultimap = owner.find(temp);///итератор на заданный элемент в multimap
owner.erase(itMultimap);///стираем его в multimap
}
void edit()
{
string temp1;
cout << "Enter edited owner" << endl;
cin >> temp1;
string temp;
auto itMultimap = owner.find(temp1);///итератор на заданный элемент в multimap
cout << "Enter new number" << endl;
cin >> temp;
itMultimap->second = temp;
}
void find()
{
string temp;
cout << "Enter seeking number" << endl;
cin >> temp;
for (multimap<string, string>::iterator it = owner.begin(); it != owner.end(); ++it)
{
if((*it).second == temp)
cout << (*it).first << " : " << (*it).second;
}
}
void sort_num_disp()
{
multimap<string, string> temp;
for (multimap<string, string>::iterator it = owner.begin(); it != owner.end(); ++it)
{
temp.insert(pair<string, string>((*it).second, (*it).first));
}
for (multimap<string, string>::iterator it = temp.begin(); it != temp.end(); ++it)
cout << (*it).first << " : " << (*it).second << endl;
}
};

int main()
{
autoOwnerDirectory aod;
aod.add();
aod.del();
aod.edit();
aod.find();
aod.sort_num_disp();
return 0;
}

Комментарии

Популярные сообщения из этого блога

ВОПРОС К ЧИТАТЕЛЯМ

Уважаемые читатели моего блога и просто проходящие мимо! У меня появилась идея заняться созданием уроков по интересующим вас темам. Предпочтительно на C++, но не ограничиваясь ими, я хочу поделиться своими знаниями не только в виде готового кода но и подробными объяснениями что к чему. Прошу вас, если вы имеете идею и хотели бы разобраться в какой-то теме - отпишитесь в комментариях, что было бы вам интересно. Постараюсь помочь. 

7 глава, Лафоре Р

*1. Напишите функцию reversit(), которая переворачивает строку (массив типа char). Используйте цикл for, который меняет местами первый и последний символы, затем следующие и т. д. до предпоследнего. Строка должна пере- даваться в функцию reversit() как аргумент. Напишите программу для выполнения функции reversit(). Программа долж- на принимать строку от пользователя, вызывать функцию reversit(), а за- тем выводить полученный результат. Используйте метод ввода, который позволяет использовать внутренние пробелы. Протестируйте программу на примере фразы «Аргентина манит негра».

6 глава, Лафоре Р

*1. Создайте класс Int, имитирующий стандартный тип int. Единственное поле этого класса должно иметь тип int. Создайте методы, которые будут устанавливать значение поля, равным нулю, инициализировать его целым значением, выводить значение поля на экран и складывать два значения типа Int. Напишите программу, в которой будут созданы три объекта класса Int, два из которых будут инициализированы. Сложите два инициализирован- ных объекта, присвойте результат третьему, а затем отобразите результат на экране.