Odpowiedź :
Odpowiedź:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>
class Product {
public:
std::string m_name{};
int m_price{};
int m_quantity{};
bool m_available{};
Product(std::string name, int price, int quantity, bool available) {
m_name = std::move(name);
m_price = price;
m_quantity = quantity;
m_available = available;
}
};
void printProducts(const std::vector<Product> &products) {
for (const auto &product: products) {
std::cout << product.m_name << std::endl;
}
}
void printCheapest(std::vector<Product> products) {
std::sort(products.begin(), products.end(),
[](const Product &a, const Product &b) { return a.m_price < b.m_price; });
std::cout << products[0].m_name << std::endl;
}
void printMostExpensive(std::vector<Product> products) {
std::sort(products.begin(), products.end(),
[](const Product &a, const Product &b) { return a.m_price > b.m_price; });
std::cout << products[0].m_name << std::endl;
}
void printAveragePrice(std::vector<Product> products) {
std::cout << std::accumulate(products.begin(), products.end(), 0.0,
[](auto accumulator, const Product &a) {
accumulator += a.m_price;
return accumulator;
}) / products.size() << std::endl;
}
void deleteQuantity(std::vector<Product> &products) {
std::string name;
std::cin >> name;
int quantity;
std::cin >> quantity;
const auto it = std::find_if(products.cbegin(), products.cend(),
[&name, &quantity](const Product &a) {
return a.m_name == name && a.m_quantity >= quantity;
});
if (it != std::cend(products)) {
const auto it2 = std::find_if(products.cbegin(), products.cend(),
[&name](const Product &a) {
return a.m_name == name;
});
const auto index = std::distance(products.cbegin(), it2);
products[index].m_quantity -= quantity;
std::cout << products[index].m_quantity << '\n';
} else {
std::cout << "Podano nieprawidlowe dane\n";
}
}
void printValue(std::vector<Product> &products) {
std::cout << std::accumulate(products.cbegin(), products.cend(), 0,
[](auto accumulator, const Product &a) {
accumulator += a.m_price * a.m_quantity;
return accumulator;
}) << '\n';
}
int main() {
Product produkt1 = Product("Mleko", 12, 3, true);
Product produkt2 = Product("Chleb", 4, 20, true);
Product produkt3 = Product("Komputer", 3000, 0, false);
std::vector<Product> products = {produkt1, produkt2, produkt3};
char n = 0;
while (true) {
std::cin >> n;
if (n == 'G') {
break;
}
switch (n) {
case 'A':
printProducts(products);
break;
case 'B':
printCheapest(products);
break;
case 'C':
printMostExpensive(products);
break;
case 'D':
printAveragePrice(products);
break;
case 'E':
deleteQuantity(products);
break;
case 'F':
printValue(products);
break;
default:
std::cout << "Podano nieobslugiwany znak\n";
break;
}
}
return 0;
}
Wyjaśnienie:
Poprawione. Jakbyś dał naj, to byłbym wdzięczny, bo trochę się namęczyłem :)