Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Generic "multi-contains" for maps

I frequently encounter the usecase where I have to check whether a set of keys is contained in a set of nested maps. I currently have an implementation for a number of practical nesting depths that look something like this:

  template< typename Key1T, typename Key2T, typename ValueT >
  bool contains
    ( std::map< Key1T, std::map< Key2T, ValueT > > const & m
    , Key1T                                        const & k1
    , Key2T                                        const & k2
    )
  {
    return m.contains( k1 ) && m.at( k1 ).contains( k2 );
  }

I was wondering if there was a way to implement this as a single function for all possible nesting depths, maybe facilitating variadic templates?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I question the motives behind doing something like this, but here you go:

template<typename FirstKey, typename InnerMap, typename... RemainingKeys>
bool contains(std::map<FirstKey, InnerMap> const& m, FirstKey const& firstKey, RemainingKeys const&... remainingKeys) {
    auto it = m.find(firstKey);
    if constexpr (sizeof...(remainingKeys) == 0) {
        return it != m.end();
    } else {
        return it != m.end() && contains(it->second, remainingKeys...);
    }
}

Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading