C++ Library - <optional>
The <optional> header is introduced in C++17, is used to represent an object in a type-safe manner that may or may not contain a value. A common use case for optional is the return value of a function that may fail.
Provides safe methods to access the contained value and clearly signifies when a value may be optional, improving code readability.
Including <optional> Header
To include the <optional> header in your C++ program, you can use the following syntax.
#include <optional>
Functions of <optional> Header
Below is list of all functions from <optional> header.
| S.NO |
Functions & Description |
| 1 |
begin
This function provides an iterator to access the stored value of an optional object if it contains a value.. |
| 2 |
emplace
This function allows you to directly construct or reconstruct the value stored in the optional object. |
| 3 |
reset
This function is used to clear the current state of the optional object.
|
| 4 |
swap
This function is used to exchange the contents of the two optional objects. |
| 5 |
value
This function is used to retrieve the value stored in the optional object.
|
Swapping Optional Values
In the following example we are going to use, std::swap to exchange the values of two objects.
#include <iostream>
#include <optional>
#include <algorithm>
int main() {
std::optional<int> a = 1;
std::optional<int> b = 2;
std::swap(a, b);
std::cout << "a: " << *a << ", b: " << *b << "\n";
return 0;
}
Output
If we run the above code it will generate the following output
a: 2, b: 1