С++ Перетворіть код так, щоб виводилось 5 найменших за кількістю товара. Кількість товару - a.num
void FiveProductLeast(const char* fn) {
Handmade a, b;
int n = 0;
int amount = AmountTovar(fn);
fopen_s(&handmade_store, fn, "rb");
do {
fread(&a, sizeof(Handmade), 1, handmade_store);
for (size_t i = 0; i < amount - 1; i++)
{
fseek(handmade_store, sizeof(Handmade) * (i + 1), SEEK_SET);
fread(&b, sizeof(Handmade), 1, handmade_store);
n++;
if (a.num > b.num) {
for (int i = 0; i < 5; i++) {
Hat();
cout << "| " << setw(3) << right << n << " "
<< "| " << setw(14) << left << a.code << " "
<< "| " << setw(26) << left << a.tovar << " "
<< "| " << setw(13) << left << a.category << " "
<< "| " << setw(17) << left << a.oznaka << " "
<< "| " << setw(8) << right << fixed << setprecision(3) << a.len << " "
<< "| " << setw(5) << right << a.num << " "
<< "| " << setw(17) << left << a.country << " "
<< "| " << setw(9) << right << setprecision(2) << a.cost << " "
<< " |" << endl;
Line();
}
}
}
} while (true);
fclose(handmade_store);
}
Answers & Comments
Handmade a;
std::vector least(5, Handmade());
std::sort(least.begin(), least.end(), [](const Handmade& a, const Handmade& b) { return a.num < b.num; });
int n = 0;
int amount = AmountTovar(fn);
fopen_s(&handmade_store, fn, "rb");
while (fread(&a, sizeof(Handmade), 1, handmade_store)) {
if (a.num < least.back().num) {
least.back() = a;
std::sort(least.begin(), least.end(), [](const Handmade& a, const Handmade& b) { return a.num < b.num; });
}
}
fclose(handmade_store);
Hat();
cout << "| " << setw(3) << right << "N" << " "
<< "| " << setw(14) << left << "Code" << " "
<< "| " << setw(26) << left << "Tovar" << " "
<< "| " << setw(13) << left << "Category" << " "
<< "| " << setw(17) << left << "Oznaka" << " "
<< "| " << setw(8) << right << "Len" << " "
<< "| " << setw(5) << right << "Num" << " "
<< "| " << setw(17) << left << "Country" << " "
<< "| " << setw(9) << right << "Cost" << " "
<< " |" << endl;
Line();
for (const auto& a : least) {
Hat();
cout << "| " << setw(3) << right << ++n << " "
<< "| " << setw(14) << left << a.code << " "
<< "| " << setw(26) << left << a.tovar << " "
<< "| " << setw(13) << left << a.category << " "
<< "| " << setw(17) << left << a.oznaka << " "
<< "| " << setw(8) << right << fixed << setprecision(3) << a.len << " "
<< "| " << setw(5) << right << a.num << " "
<< "| " << setw(17) << left << a.country << " "