std::map default value

后端 未结 12 2068
旧巷少年郎
旧巷少年郎 2020-11-28 06:09

Is there a way to specify the default value std::map\'s operator[] returns when an key does not exist?

12条回答
  •  清歌不尽
    2020-11-28 06:46

    Expanding on the answer https://stackoverflow.com/a/2333816/272642, this template function uses std::map's key_type and mapped_type typedefs to deduce the type of key and def. This doesn't work with containers without these typedefs.

    template 
    typename C::mapped_type getWithDefault(const C& m, const typename C::key_type& key, const typename C::mapped_type& def) {
        typename C::const_iterator it = m.find(key);
        if (it == m.end())
            return def;
        return it->second;
    }
    

    This allows you to use

    std::map m;
    int* v = getWithDefault(m, "a", NULL);
    

    without needing to cast the arguments like std::string("a"), (int*) NULL.

提交回复
热议问题