Advertisement
CR7CR7

sortProduct

Aug 9th, 2023
1,172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.58 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4.  
  5. class Product {
  6. public:
  7.     std::string name;
  8.     std::string type;
  9.     double price;
  10.  
  11.     Product(const std::string& name, const std::string& type, double price)
  12.         : name(name), type(type), price(price) {}
  13. };
  14.  
  15. bool compareByPrice(const Product& p1, const Product& p2) {
  16.     return p1.price < p2.price;
  17. }
  18.  
  19. int main() {
  20.     std::vector<Product> products;
  21.  
  22.     // Add some sample products
  23.     products.push_back(Product("Laptop", "Tech", 999.99));
  24.     products.push_back(Product("Smartphone", "Tech", 799.99));
  25.     products.push_back(Product("Headphones", "Tech", 199.99));
  26.     products.push_back(Product("TV", "Tech", 1499.99));
  27.  
  28.     // Sort the products by price
  29.     std::sort(products.begin(), products.end(), compareByPrice);
  30.  
  31.     // Print the sorted products
  32.     std::cout << "Sorted products by price:" << std::endl;
  33.     for (const auto& product : products) {
  34.         std::cout << product.name << " - $" << product.price << std::endl;
  35.     }
  36.  
  37.     // Search for a product by name
  38.     std::string searchName;
  39.     std::cout << "Enter the name of the product to search: ";
  40.     std::cin >> searchName;
  41.  
  42.     // Find the product by name
  43.     bool found = false;
  44.     for (const auto& product : products) {
  45.         if (product.name == searchName) {
  46.             std::cout << "Price of " << product.name << ": $" << product.price << std::endl;
  47.             found = true;
  48.             break;
  49.         }
  50.     }
  51.  
  52.     if (!found) {
  53.         std::cout << "Product is not available" << std::endl;
  54.     }
  55.  
  56.     return 0;
  57. }
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement