Back
Close

Modern C++ idoms and recipes

meshell
13K views

std::optional

C++17 adds template std::optional to manage an optional value.

DIY

Try to make pass the tests for error cases. Do not worry about the good case test, if it fails because of formating or precision issues.

Make the tests pass by refactoring function differentiate to return std::optional<double> instead of double. Does it help to make use of value_or()?

Refactor the code to use std::optional
#include <functional>
#include <sstream>
#include <string>
// symmetric difference quotient
double differentiate(std::function<double(double)> f, double h, double x)
{
return (f(x + h) - f(x - h)) / (2 * h);
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Bonus exercise

Replace the type for time with something better than than double.

Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants