Perhaps I did something wrong with the vector of structures, for the first time I work with this one. Please help me if you know what the matter is)

#include "stdafx.h" #include<iostream> #include<conio.h> #include<vector> using namespace std; struct money { int Rubles, Kopecks; }; int main() { int n, k,max1, max2, min1, min2; setlocale(LC_ALL, "Russian"); cout << "ΠŸΡ€ΠΎΠ³Ρ€Π°ΠΌΠΌΠ° Π²Ρ‹Π²ΠΎΠ΄ΠΈΡ‚ ΠΌΠ°ΠΊΡΠΈΠΌΠ°Π»ΡŒΠ½ΡƒΡŽ ΠΈ ΠΌΠΈΠ½ΠΈΠΌΠ°Π»ΡŒΠ½ΡƒΡŽ Π΄Π΅Π½Π΅ΠΆΠ½ΡƒΡŽ суммы" << endl; cout << "Π’Π²Π΅Π΄ΠΈΡ‚Π΅ количСство Π΄Π΅Π½Π΅ΠΆΠ½Ρ‹Ρ… сумм" << endl; cin >> n; vector <money> a; a.reserve(n); for (int i = 0; i < n; i++) { cout << "Π’Π²Π΅Π΄ΠΈΡ‚Π΅ количСство Ρ€ΡƒΠ±Π»Π΅ΠΉ " << i + 1 << "-ΠΎΠΉ Π΄Π΅Π½Π΅ΠΆΠ½ΠΎΠΉ суммы" << endl; cin >> a[i].Rubles; cout << "Π’Π²Π΅Π΄ΠΈΡ‚Π΅ количСство ΠΊΠΎΠΏΠ΅Π΅ΠΊ " << i + 1 << "-ΠΎΠΉ Π΄Π΅Π½Π΅ΠΆΠ½ΠΎΠΉ суммы" << endl; cin >> a[i].Kopecks; if (a[i].Kopecks >= 100) { k = a[i].Kopecks / 100; a[i].Kopecks -= k * 100; a[i].Rubles += k; } } max1=a[0].Rubles; max2=a[0].Kopecks; for (int i = 1; i < n; i++) { if (a[i].Rubles > max1) { max1 = a[i].Rubles; max2 = a[i].Kopecks; } if (a[i].Rubles == max1) if (a[i].Kopecks > max2) max2 = a[i].Kopecks; } min1 = a[0].Rubles; min2 = a[0].Kopecks; for (int i = 1; i < n; i++) { if (a[i].Rubles < min1) { min1 = a[i].Rubles; min2 = a[i].Kopecks; } if (a[i].Rubles == min1) if (a[i].Kopecks < min2) min2 = a[i].Kopecks; } cout << "Максимальная сумма: " << max1 << "Ρ€ΡƒΠ±Π»Π΅ΠΉ " << max2 << "ΠΊΠΎΠΏΠ΅Π΅ΠΊ" << endl; cout << "Минимальная сумма: " << min1 << "Ρ€ΡƒΠ±Π»Π΅ΠΉ " << max2 << "ΠΊΠΎΠΏΠ΅Π΅ΠΊ" << endl; _getch(); return 0; } 

    2 answers 2

    vector::reserve allocates memory just in case, but does not allow access. Need to use vector::resize

      It is better to write the same thing on the principle of OOP

       #include <iostream> #include <vector> using namespace std; struct money { int Rubles, Kopecks; friend std::istream& // Ρ‡Ρ‚ΠΎΠ±Ρ‹ Π²Π²ΠΎΠ΄ΠΈΡ‚ΡŒ сразу ΠΎΠ±ΡŒΠ΅ΠΊΡ‚ operator >>(std::istream& is, money& m) { is >> m.Rubles >> m.Kopecks; int k = m.Kopecks / 100; if ( k ) { m.Kopecks -= k * 100; m.Rubles += k; } return is; } bool operator <(const money& m) //для сортировки { if (Rubles == m.Rubles) return Kopecks < m.Kopecks; return Rubles < m.Rubles; } }; int main() { int n{}; cin >> n; vector<money> a(n); // сразу создаСм Π²Π΅ΠΊΡ‚ΠΎΡ€ Ρ€Π°Π·ΠΌΠ΅Ρ€Π° n for (int i = 0; i < n; ++i) { cout << "Π’Π²Π΅Π΄ΠΈΡ‚Π΅ количСство Ρ€ΡƒΠ±Π»Π΅ΠΉ ΠΈ ΠΊΠΎΠΏΠ΅Π΅ΠΊ " << i + 1 << "-ΠΎΠΉ Π΄Π΅Π½Π΅ΠΆΠ½ΠΎΠΉ суммы" << endl; cin >> a[i]; } sort(a.begin(), a.end()); money max = a[n - 1], min = a[0]; cout << "Максимальная сумма: " << max.Rubles << " Ρ€ΡƒΠ±Π»Π΅ΠΉ " << max.Kopecks << " ΠΊΠΎΠΏΠ΅Π΅ΠΊ" << endl; cout << "Минимальная сумма: " << min.Rubles << "Ρ€ΡƒΠ±Π»Π΅ΠΉ " << min.Kopecks << "ΠΊΠΎΠΏΠ΅Π΅ΠΊ" << endl; return 0; }