Загрузка данных
#include <iostream>
#include <complex>
#include <limits>
#include <string>
using namespace std;
// ==================== ПЕРЕГРУЗКА ОПЕРАТОРОВ ДЛЯ COMPLEX ====================
istream& operator>>(istream& in, complex<double>& c) {
double real, imag;
if (in >> real >> imag) {
c = complex<double>(real, imag);
} else {
in.setstate(ios::failbit);
}
return in;
}
ostream& operator<<(ostream& out, const complex<double>& c) {
out << "(" << c.real() << "," << c.imag() << ")";
return out;
}
// ==================== УНИВЕРСАЛЬНАЯ ФУНКЦИЯ ВВОДА С ПРОВЕРКОЙ ====================
template<typename T>
T inputValue(const char* prompt) {
T value;
bool valid = false;
for (int attempt = 0; attempt < 3 && !valid; attempt++) {
cout << prompt;
if (cin >> value) {
valid = true;
} else {
cin.clear();
cin.ignore(10000, '\n');
cout << "Oshibka! Vvedite chislo. ";
}
}
if (!valid) {
cout << "Prekratnyy vvod. Ustanovleno znachenie 0." << endl;
value = T();
}
return value;
}
// ==================== ВСПОМОГАТЕЛЬНАЯ ФУНКЦИЯ ДЛЯ ВЫЧИСЛЕНИЯ СРЕДНЕГО ====================
template<typename T>
double computeAverage(T sum, int rows) {
return static_cast<double>(sum) / rows;
}
// Специализация для complex<double>
template<>
double computeAverage<complex<double>>(complex<double> sum, int rows) {
complex<double> avg = sum / static_cast<double>(rows);
return abs(avg);
}
// ==================== ШАБЛОН ФУНКЦИИ ДЛЯ РЕШЕНИЯ ЗАДАЧИ ====================
template<typename T>
int findColumnWithMinAverage(T** arr, int rows, int cols) {
if (rows <= 0 || cols <= 0) {
return -1;
}
int minCol = 0;
double minAverage = numeric_limits<double>::max();
for (int j = 0; j < cols; j++) {
T sum = T(); // сумма элементов в столбце
// Вычисляем сумму элементов столбца
for (int i = 0; i < rows; i++) {
sum = sum + arr[i][j];
}
// Вычисляем среднее арифметическое с помощью вспомогательной функции
double average = computeAverage(sum, rows);
if (average < minAverage) {
minAverage = average;
minCol = j;
}
}
return minCol;
}
// ==================== ФУНКЦИЯ ДЛЯ ТЕСТИРОВАНИЯ ====================
template<typename T>
void testMatrix(const string& typeName) {
int rows, cols;
cout << "\n========== TEST: " << typeName << " ==========" << endl;
rows = inputValue<int>("Vvedite kolichestvo strok: ");
cols = inputValue<int>("Vvedite kolichestvo stolbcov: ");
if (rows <= 0 || cols <= 0) {
cout << "Nekorrektnyy razmer matricy!" << endl;
return;
}
T** matrix = new T*[rows];
for (int i = 0; i < rows; i++) {
matrix[i] = new T[cols];
}
cout << "Vvedite elementy matricy " << rows << "x" << cols << ":" << endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
string prompt = " [" + to_string(i) + "][" + to_string(j) + "] = ";
matrix[i][j] = inputValue<T>(prompt.c_str());
}
}
cout << "\nMatrica:" << endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << matrix[i][j] << "\t";
}
cout << endl;
}
int resultCol = findColumnWithMinAverage(matrix, rows, cols);
if (resultCol != -1) {
cout << "\nStolec s minimal'nym srednim arifmeticheskim: " << resultCol << endl;
cout << "Nomer stolbca (schityaya s 1): " << resultCol + 1 << endl;
} else {
cout << "\nMatrica pusta!" << endl;
}
for (int i = 0; i < rows; i++) {
delete[] matrix[i];
}
delete[] matrix;
}
// ==================== ГЛАВНАЯ ФУНКЦИЯ ====================
int main() {
cout << "Programma ischet nomer stolbca s minimal'nym srednim arifmeticheskim." << endl;
cout << "===================================================================" << endl;
testMatrix<int>("int");
testMatrix<double>("double");
testMatrix<complex<double>>("complex<double>");
return 0;
}
аааааааааааааааа
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// ==================== ФУНКЦИЯ ДЛЯ ВВОДА ЦЕЛЫХ ЧИСЕЛ С ПРОВЕРКОЙ ====================
int inputInt(const char* prompt) {
int value;
bool validInput = false;
cout << prompt;
for (int attempt = 0; attempt < 3 && !validInput; attempt++) {
if (attempt > 0) {
cout << "Oshibka! Vvedite chislo: ";
}
if (cin >> value) {
if (value > 0) {
validInput = true; // число положительное
} else {
cout << "Chislo dolzhno byt' bol'she 0. ";
cin.clear();
cin.ignore(10000, '\n');
}
} else {
cin.clear();
cin.ignore(10000, '\n');
cout << "Nekorrektnyy vvod. ";
}
}
if (!validInput) {
cout << "Prekratnyy vvod. Ustanovleno znachenie 1." << endl;
value = 1;
}
return value;
}
// ==================== ФУНКЦИЯ ДЛЯ ВВОДА МАССИВА С ПРОВЕРКОЙ ====================
void inputArray(vector<int>& arr, int size) {
for (int i = 0; i < size; i++) {
char prompt[100];
sprintf(prompt, "X[%d] = ", i);
arr[i] = inputInt(prompt);
}
}
// ==================== ГЛАВНАЯ ФУНКЦИЯ ====================
int main() {
const int SIZE = 20;
vector<int> X(SIZE);
// Ввод элементов массива с проверкой
cout << "Vvedite " << SIZE << " elementov massiva X (polozhitel'nye chisla):" << endl;
inputArray(X, SIZE);
// Вывод исходного массива
cout << "\nIshodnyy massiv X:" << endl;
for (int i = 0; i < SIZE; i++) {
cout << X[i] << " ";
}
cout << endl;
// Поиск индекса максимального элемента
int maxIndex = 0;
for (int i = 1; i < SIZE; i++) {
if (X[i] > X[maxIndex]) {
maxIndex = i;
}
}
cout << "\nIndeks maksimal'nogo elementa: " << maxIndex << endl;
cout << "Maksimal'nyy element: " << X[maxIndex] << endl;
// Создание дополнительного массива Y
vector<int> Y;
// Перенос элементов, индексы которых больше maxIndex
for (int i = maxIndex + 1; i < SIZE; i++) {
Y.push_back(X[i]);
}
// Вывод результата
cout << "\nPoluchennyy massiv Y:" << endl;
if (Y.empty()) {
cout << "Massiv pust" << endl;
} else {
for (int i = 0; i < Y.size(); i++) {
cout << Y[i] << " ";
}
cout << endl;
}
cout << "Razmer poluchennogo massiva: " << Y.size() << endl;
return 0;
}
ааааааааааааааа
#include <iostream>
#include <list>
#include <string>
using namespace std;
// ==================== ФУНКЦИЯ ДЛЯ ВВОДА ЦЕЛЫХ ЧИСЕЛ С ПРОВЕРКОЙ ====================
int inputInt(const char* prompt) {
int value;
bool validInput = false;
cout << prompt;
for (int attempt = 0; attempt < 3 && !validInput; attempt++) {
if (attempt > 0) {
cout << "Oshibka! Vvedite chislo: ";
}
if (cin >> value) {
if (value > 0) {
validInput = true;
} else {
cout << "Chislo dolzhno byt' bol'she 0. ";
cin.clear();
cin.ignore(10000, '\n');
}
} else {
cin.clear();
cin.ignore(10000, '\n');
cout << "Nekorrektnyy vvod. ";
}
}
if (!validInput) {
cout << "Prekratnyy vvod. Ustanovleno znachenie 1." << endl;
value = 1;
}
return value;
}
// ==================== СТРУКТУРА ФИЛЬМ ====================
struct Film {
string nazvanie; // название фильма
int stoimost; // стоимость
string rezhisser; // режиссер
};
// ==================== ФУНКЦИЯ ДЛЯ ВЫВОДА ФИЛЬМА ====================
void printFilm(const Film& f, int index) {
cout << " " << index + 1 << ". " << f.nazvanie;
cout << " | Stoimost': " << f.stoimost;
cout << " | Rezhisser: " << f.rezhisser << endl;
}
// ==================== ФУНКЦИЯ ДЛЯ ВВОДА ФИЛЬМА ====================
void inputFilm(Film& f, int index) {
cout << "\n--- Film #" << index + 1 << " ---" << endl;
cout << "Nazvanie: ";
cin >> f.nazvanie;
f.stoimost = inputInt("Stoimost': ");
cout << "Rezhisser: ";
cin >> f.rezhisser;
}
// ==================== ФУНКЦИЯ ДЛЯ ВЫВОДА ФИЛЬМОВ РЕЖИССЁРА ====================
void printFilmsByRezhisser(const list<Film>& videoteka, const string& rezhisser) {
cout << "\n========== FIL'MY REZhISSERA \"" << rezhisser << "\" ==========" << endl;
int count = 0;
int index = 0;
for (list<Film>::const_iterator it = videoteka.begin(); it != videoteka.end(); ++it) {
if (it->rezhisser == rezhisser) {
printFilm(*it, index);
count++;
}
index++;
}
if (count == 0) {
cout << "Filmow rezhissera \"" << rezhisser << "\" ne naydeno." << endl;
} else {
cout << "\nVsego nashli " << count << " filmow." << endl;
}
}
// ==================== ФУНКЦИЯ ДЛЯ ВЫВОДА ВСЕЙ ВИДЕОТЕКИ ====================
void printAllFilms(const list<Film>& videoteka) {
if (videoteka.empty()) {
cout << "Videoteka pusta." << endl;
return;
}
cout << "\n========== VSYa VIDEOTEKA ==========" << endl;
int index = 0;
for (list<Film>::const_iterator it = videoteka.begin(); it != videoteka.end(); ++it) {
printFilm(*it, index);
index++;
}
}
// ==================== ФУНКЦИЯ ДЛЯ ВВОДА ВСЕЙ ВИДЕОТЕКИ ====================
void inputVideoteka(list<Film>& videoteka, int n) {
for (int i = 0; i < n; i++) {
Film f;
inputFilm(f, i);
videoteka.push_back(f);
}
}
// ==================== ГЛАВНАЯ ФУНКЦИЯ ====================
int main() {
list<Film> videoteka;
int n;
// Ввод количества фильмов
cout << "Skolko filmov vvesti? ";
n = inputInt("");
// Ввод информации о фильмах
inputVideoteka(videoteka, n);
// Вывод всей видеотеки
printAllFilms(videoteka);
// Запрос режиссёра для поиска
string searchRezh;
cout << "\nVvedite familiyu rezhissera: ";
cin >> searchRezh;
// Вывод фильмов указанного режиссёра
printFilmsByRezhisser(videoteka, searchRezh);
return 0;
}