Solving a Comprehensive Problem with Ranges
Lesson Introduction
In today's lesson, we'll explore a comprehensive problem using the Boost.Range library in C++. Completing this lesson will help you understand how to use ranges to solve complex tasks systematically. Our goal is to calculate the average price of houses that cost more than 50,000 by filtering, transforming, and accumulating values—operations that Boost.Range simplifies tremendously.
Understanding the Problem
Imagine you have a dataset filled with house prices. Our task is to find the average price of these houses, but only for those that cost more than 50,000. This problem involves multiple steps: filtering out houses costing 50,000 or less, applying a 10% discount to each remaining house price, and then calculating the average price. Let's see how we can achieve this efficiently with Boost.Range.
Setting Up
First, we'll introduce the necessary libraries and set up our data. Here's a code snippet for reference:
A vector is a dynamic array that can grow as needed, making it suitable for storing integer prices. The given array contains both houses costing more and less than 50,000.
Filtering with Boost.Range
Next, we need to filter out the houses costing 50,000 or less. Boost.Range provides the boost::adaptors::filtered functionality to achieve this:
Here, boost::adaptors::filtered uses a lambda function to filter out prices less than or equal to 50,000. The lambda function [](int price) { return price > 50000; } returns true for prices greater than 50,000, allowing them to pass through the filter.
Transforming with Boost.Range
Once filtered, we want to apply a 10% discount to the remaining prices. This is done using boost::adaptors::transformed:
The transformation uses another lambda function, [](int price) { return price * 0.90; }, which applies a 10% discount to each filtered price. We use the pipe operator to combine them
