C++ optional::begin() Function



The std::optional::begin() function in C++, provides an iterator to access the stored value of an optional object if it contains a value. It is used for interacting with optional values in a container-like manner.

If the optional object is not empty, begin() returns a iterator pointing to that value otherwise it returns the past the end iterator.

Syntax

Following is the syntax for std::optional::begin() function.

 iterator begin() noexcept; or const_iterator begin() const noexcept; 

Parameters

It does not accepts any parameter.

Return value

This function returns the iterator to the contained value.

Example 1

Let's look at the following example, where we are going to accessing optional with begin().

 #include <iostream> #include <optional> #include <vector> int main() { std::optional < std::vector < int >> x = std::vector < int > {11,2,33}; if (x) { auto a = x -> begin(); std::cout << "Result : " << * a << std::endl; } else { std::cout << "Is empty!" << std::endl; } return 0; } 

Output

Output of the above code is as follows −

 Result : 11 

Example 2

Consider the following example, where we are going to use the optional() to iterate through elements.

 #include <iostream> #include <optional> #include <vector> int main() { std::optional < std::vector < int >> a = std::vector < int > {12,23,34}; if (a) { for (auto x = a -> begin(); x != a -> end(); ++x) { std::cout << * x << " "; } std::cout << std::endl; } else { std::cout << "Is empty!" << std::endl; } return 0; } 

Output

Output of the above code is as follows −

 12 23 34 

Example 3

In the following example, we are going to use the empty optional and applying the begin() function.

 #include <iostream> #include <optional> #include <vector> int main() { std::optional < std::vector < int >> a; if (a) { auto x = a -> begin(); std::cout << "Result : " << * x << std::endl; } else { std::cout << "Optional is empty." << std::endl; } return 0; } 

Output

If we run the above code it will generate the following output −

 Optional is empty. 
cpp_optional.htm
Advertisements