Skip to content

Search is only available in production builds. Try building and previewing the site to test it out locally.

⚙️Tutorial: C++ STL

C++ Standard Library Tutorial: Programming for an Edge Environmental Sensor

Section titled “C++ Standard Library Tutorial: Programming for an Edge Environmental Sensor”

Welcome to this practical tutorial on using the C++ Standard Library for edge programming. The following exercises are designed to help you apply the concepts from the course notes to a real-world scenario. We will be developing small pieces of software for a hypothetical environmental sensor that reads temperature, humidity, and air quality data.

Each question builds on the last, guiding you from basic data storage to more advanced memory management and algorithmic processing.

Good luck!


Your sensor takes ten temperature readings and needs to store them in memory. Write a C++ program that uses the most appropriate STL sequential container to store the following floating-point values: 19.5, 20.3, 20.8, 20.1, 19.8, 19.9, 21.0, 20.5, 20.7, 21.2.

After storing the values, use a range-based for loop in a function called printReadings() that accepts your container as a parameter to print each reading to the console. Keep your solution code for Question 3.


Question 2: Associating Readings with Timestamps

Section titled “Question 2: Associating Readings with Timestamps”

Storing just the readings isn’t enough; you need to know when they were taken. Modify your program to use an STL associative container to store the temperature readings from Question 1, associating each one with a timestamp (you can use an integer for simplicity, e.g., 1001, 1002, …).

Modify your printReadings() function to print out each timestamp and its corresponding temperature reading.


Your sensor’s quality control routine needs to check if a specific, potentially anomalous, reading exists in a data set. Using the original std::vector of temperatures from Question 1, use an STL algorithm to find the reading 21.0. Write a function that uses the find() algorithm and prints a message indicating whether the reading was found or not.


Question 4: Calculating the Average Temperature

Section titled “Question 4: Calculating the Average Temperature”

To report a daily summary, the sensor needs to calculate the average of its readings. Using the std::vector of temperatures from Question 1 and the numeric STL algorithm accumulate (which is in the <numeric> header file) calculate the sum of all the readings and then compute and print the average temperature. Check if the vector is empty before performing the calculation.


Question 5: Processing Data with a Functor

Section titled “Question 5: Processing Data with a Functor”

The sensor needs to send its data to a system that requires temperatures in Fahrenheit. Create a “functor” (a struct or class with an overloaded operator()) that converts a Celsius value to Fahrenheit (F = C * 9/5 + 32).

Use the std::transform algorithm to create a new std::vector containing the Fahrenheit temperatures. Print the new vector.


Question 6: Simplifying with a Lambda Function

Section titled “Question 6: Simplifying with a Lambda Function”

Functors are powerful but can be verbose for simple, one-off operations. Repeat the Celsius-to-Fahrenheit conversion from Question 5, but this time use a C++11 lambda function instead of a named functor class.


Question 7: Managing a Dynamic Configuration

Section titled “Question 7: Managing a Dynamic Configuration”

Your sensor needs to load a special configuration file from memory. Write a function loadConfig() that simulates this by dynamically allocating an integer array (of size 3) on the heap representing configuration values. In main, call this function to get a pointer to the config, print the values, and then demonstrate what happens if you forget to delete the memory (i.e., a memory leak).

For this question, using a raw pointer is intentional.


Question 8: Safe Configuration Management with std::unique_ptr

Section titled “Question 8: Safe Configuration Management with std::unique_ptr”

Fix the memory leak from Question 7. Refactor the loadConfig() function and your main function to use a std::unique_ptr. This smart pointer should manage the dynamically allocated configuration, ensuring it is automatically deleted when it goes out of scope.


Question 9: Handling a Shared Logging Service

Section titled “Question 9: Handling a Shared Logging Service”

Your sensor system has a central logging service that multiple components need to access. Create a simple Logger class. In main, create a Logger object on the heap and manage it with a std::shared_ptr. Create a second shared_ptr from the first one to simulate another component also using the logger.

Print the use_count() of the shared_ptr to demonstrate how many pointers are sharing ownership.


Question 10: Breaking Ownership Cycles with std::weak_ptr

Section titled “Question 10: Breaking Ownership Cycles with std::weak_ptr”

A more complex scenario arises. You have a Sensor class and a DeviceController class. The DeviceController needs to own and manage the Sensor. However, the Sensor also needs a way to notify its controller of events, so it needs a pointer back to the DeviceController. If you use std::shared_ptr for both pointers, you will create a circular reference and a memory leak.

Fix this by using a std::weak_ptr in the Sensor class to hold a non-owning reference back to its controller.


change Question 11: Modernising with Ranges (C++20)

Section titled “change Question 11: Modernising with Ranges (C++20)”

Refactor your solution for Question 3 or Question 4 to use C++20 Ranges. For example, use std::ranges::find() instead of std::find(). Additionally, explore how std::views::filter could be used to extract and print only the temperatures from Question 1 that are above a certain threshold (e.g., above 20.0).


Here are the video solutions — please do not watch these solutions without having attempted the questions first. Please note that these solutions are somewhat warts and all in that I make errors and correct them live without edits.

Alternatively, you can view the video directly on YouTube: https://www.youtube.com/watch?v=dx9cb2P2rYU