In C++, std::optional is a powerful feature introduced in C++17 that represents an object that may or may not contain a value. It’s often used to handle cases where you want to signify that a value might be absent, thus providing a safer and more expressive way to manage optional data without resorting to pointers or special value indicators.
To use std::optional, you first need to include the header:
#include <optional> #include <iostream> int main() { std::optionalopt; // Default initialization, opt has no value if (!opt.has_value()) { std::cout << "opt is empty" << std::endl; } opt = 42; // Assign a value to opt if (opt.has_value()) { std::cout << "opt contains: " << *opt << std::endl; // Dereferencing to access value } // Reset the optional to be empty again opt.reset(); if (!opt) { std::cout << "opt is now empty again" << std::endl; } return 0; }
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?