Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why std::map does not have a FindOrNull method

Tags:

c++

FindOrNull is so much more concise than the build-in find. Compare

    auto& map = GetMap()
    if (auto iter = map.find("key"); iter != map.end()) {
       // use iter.second
    }

With

    if (auto value = GetMap().find_or_null("key")) {
       // use *value
    }

like image 740
yufanyufan Avatar asked Oct 24 '25 18:10

yufanyufan


1 Answers

First of all std::map can contain anything. It can be a pointer (then null makes sense, but it contain a value then null has no meaning).

To overcome this you can just use a helper:

template<typename T, typename K>
auto get_optional_value(T&& map, K&& key)
{
    auto it = map.find(std::forward<K>(key));
    if (it == map.end()) return std::optional<typename std::decay<T>::type::mapped_type>{};
    return std::optional<typename std::decay<T>::type::mapped_type>{it->second};
}

https://wandbox.org/permlink/TS56MAb97NQXkepj

Note that std::optional is quite fresh c++17.

like image 77
Marek R Avatar answered Oct 26 '25 09:10

Marek R