Optional Type in C++
Level 5388 keystrokes
findIndex returns optional<int>: the index when the value is found, or nullopt when it is not. The caller checks with has_value() before reading value(); has_value() prints as 0 for false.
C++ code
// The return type says the result may be missing1optional<int> findIndex(const vector<int>& v, int target) { // Checks each element in order2 for (int i = 0; i < v.size(); i++) { // Found: the int i is wrapped in an optional automatically3 if (v[i] == target) return i;4 } // Not found: nullopt means "no value"5 return nullopt;6}7 8vector<int> nums = {10, 20, 30, 40, 50};9 // if with an initializer (C++17): idx exists only inside this if10if (auto idx = findIndex(nums, 30); idx.has_value()) { // value() reads the index: prints "Found at index: 2"11 cout << "Found at index: " << idx.value() << endl;12}13 // 99 is not in the vector, so this is nullopt14auto missing = findIndex(nums, 99);// Without boolalpha, false prints as 0: "Has value: 0"15cout << "Has value: " << missing.has_value() << endl;Output
Found at index: 2 Has value: 0
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this C++ code and how often they appear.
<× 16(× 10)× 10;× 9,× 7=× 6.× 4"× 4{× 4}× 4