/** * Clayton Cafiero * CS 2240 * 2021-Jan-22 */ /** * We want `` so we can use in our hash table, * i.e. some elements have values, others do not, hence * `nullopt`. We've been using C++ 14 standard so far for * this class, and optional was introduced in C++ 17. * So here we try to include if * standard is < 17, if that fails we go with C++ version * * * If this produces errors, go into CMakeLists.txt and change * the CMAKE_CXX_STANDARD from 14 to 17. * * Here also is a valid use case for `using` in a header * file. We want `optional`, `nullopt`, and `make_optional`, * but these reside in different scopes in C++ 14 vs C++ 17. * Hence we apply `using` here, so that the code in our * header is portable between 14 and 17. Notice that we don't * use the entire namespace, just what we actually use. */ #if __cplusplus < 17 #include using std::experimental::optional; using std::experimental::nullopt; using std::experimental::make_optional; #else #include using std::optional; using std::nullopt; using std::make_optional; #endif #include #include #include optional find(std::vector& v, std::string key) { for (int i = 0; i < v.size(); ++i) { if (v[i] == key) { return i; } } return nullopt; } int main() { std::vector v = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}; optional i = find(v, "Thursday"); if (i) { std::cout << *i << std::endl; } i = find(v, "Wombat"); if (i) { // won't print! 'cause "Wombat" is not in our vector // and thus find will return nullopt std::cout << *i << std::endl; } return 0; }