How to use the ranges::for_each function to applies a unary function object to elements in a range in C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

// Define a simple data structure
struct Product {
    std::string name;
    double price;
};

// Function demonstrating ranges::for_each with and without projections
void update_and_display_inventory(std::vector<Product>& inventory) {
    
    // 1. Using projections to apply a 10% discount directly to the 'price' member
    // The projection &Product::price extracts the double before passing it to the lambda.
    std::ranges::for_each(inventory, [](double& price) {
        price *= 0.90; // Apply 10% discount
    }, &Product::price);

    // 2. Using ranges::for_each to iterate over the entire range and print details
    std::ranges::for_each(inventory, [](const Product& p) {
        std::cout << "Product: " << p.name << " | Discounted Price: $" << p.price << "\n";
    });
}

int main() {
    // Initialize a vector of products
    std::vector<Product> store_inventory = {
        {"Laptop", 1200.0},
        {"Mouse", 25.0},
        {"Keyboard", 75.0}
    };

    update_and_display_inventory(store_inventory);
}


/*
run:

Product: Laptop | Discounted Price: $1080
Product: Mouse | Discounted Price: $22.5
Product: Keyboard | Discounted Price: $67.5

*/

 



answered Oct 28 by avibootz
...