Untitled
unknown
c_cpp
22 days ago
5.0 kB
0
Indexable
Never
//Напиши программу, которая заполняет вектор объектами класса Rectangle. Стороны каждого прямоугольника вводит пользователь. Сделай проверку ввода. // Отсортируй вектор с помощью функции sort (algorithm) по возрастанию площади. #include <iostream> #include <cmath> #include <vector> #include <cstdlib> #include <ctime> #include <windows.h> #include <algorithm> using namespace std; class MyRectangle { private: int a, b; public: int GetA() const { return a; } int GetB() const { return b; } void SetA( const int a ) { if ( a > 0 ) this->a = a; } void SetB( const int b ){ if ( b > 0 ) this->a = a; } //конструктор 2 в 1 MyRectangle(const int a = 1, const int b = 1): a(a), b(b) { } //вычисление площади int Area() const { return a * b; } }; bool operator> ( const MyRectangle& first, const MyRectangle& second ) { return first.Area() > second.Area(); } bool operator< ( const MyRectangle& first, const MyRectangle& second ) { return first.Area() < second.Area(); } ostream& operator<< ( ostream& os, const MyRectangle& pl) { os << "(" << pl.GetA() << "; " << pl.GetB() << ")"; return os; } struct { bool operator()( const MyRectangle& a, const MyRectangle& b) const { return a < b; } } CompareArea; void FillVec( vector <MyRectangle> &vec, const int count ); void PrintVec( const vector <MyRectangle> &vec ); int Menu( const int low, const int high, const string &mes ); // функция меню int main() { SetConsoleCP( 1251 ); SetConsoleOutputCP( 1251 ); srand( time( 0 )); vector<MyRectangle> pVec; int n; cout << "Введите количесвто прямоугольников"; cin >> n; FillVec( pVec); PrintVec( pVec ); sort( pVec.begin(), pVec.end(), CompareArea ); PrintVec( pVec ); while ( true ) { // пока правда int key = Menu( 0, 3, "Выберите пункт" ); if ( !key ) break; switch ( key ) { //выбор case 1: { cout << "\nВведите элемент вектора для добавления: "; int a = GetNaturalNumber(1, 100, " "); int b = GetNaturalNumber(1, 100, " "); MyRectangle rect( a, b ); pVec.push_back( rect ); break; } case 2: { pVec.clear(); cout << "\nВведите количесвто для удаления из вектора: "; int n = GetNaturalNumber( 1, 100 , "Введите число "); FillVec(pVec); break; } case 3 : { PrintVec( pVec ); cout << endl; break; } case 4: { // заглушка break; } } } return 0; return 0; } int Menu( const int low, const int high, const string &mes = "" ) { // cout << "1 - Добавить строны вручную\n"; cout << "2 - добавить случайными числами\n"; cout << "3 - Вывести на экран\n"; cout << "4 - Сортировка\n"; cout << "0 - выход" << endl; int key = GetNaturalNumber( low, high, mes ); return key; } //функция на правильность вводв int GetNaturalNumber( const int low, const int high, const string &mes ) { // low - нижняя граница, high - верхняя граница string nStr; int n; while ( true ) { cout << mes << " от " << low << " до " << high << ": "; getline( cin, nStr ); // считываем строку неограниченной длины, до нажатия Enter // пробуем найти ЛЮБОЙ символ, НЕ входящий в набор 0123456789 if ( nStr.find_first_not_of( "0123456789" ) == string::npos ) { // если НЕ нашли, то введено целое число stringstream ss; ss << nStr; // отдаём строковому потоку строку, которая представляет собой запись целого полоительного числа ss >> n; // просим строковый поток вернуть нам int значение if ( n >= low && n <= high ) break; } cout << "Ошибка ввода! Значение должно быть " << "от " << low << " до " << high << "!" << endl; } return n; } void FillVec( vector <MyRectangle> &vec ){ for (int i = 0; i < count; ++i) { MyRectangle p( rand() % 101 - 50, rand() % 101 - 50 ); vec.push_back( p ); } } void PrintVec( const vector <MyRectangle> &vec){ for( const MyRectangle& p : vec ) cout << p << " "; }