std::map 默认值

新手上路,请多包涵

有没有办法指定默认值 std::mapoperator[] 当密钥不存在时返回?

原文由 anon 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 805
2 个回答

不,没有。最简单的解决方案是编写自己的免费模板函数来执行此操作。就像是:

 #include <string>
#include <map>
using namespace std;

template <typename K, typename V>
V GetWithDef(const  std::map <K,V> & m, const K & key, const V & defval ) {
   typename std::map<K,V>::const_iterator it = m.find( key );
   if ( it == m.end() ) {
      return defval;
   }
   else {
      return it->second;
   }
}

int main() {
   map <string,int> x;
   ...
   int i = GetWithDef( x, string("foo"), 42 );
}


C++11 更新

目的:说明通用关联容器,以及可选的比较器和分配器参数。

 template <template<class,class,class...> class C, typename K, typename V, typename... Args>
V GetWithDef(const C<K,V,Args...>& m, K const& key, const V & defval)
{
    typename C<K,V,Args...>::const_iterator it = m.find( key );
    if (it == m.end())
        return defval;
    return it->second;
}

原文由 anon 发布,翻译遵循 CC BY-SA 3.0 许可协议

这是一种正确的方法,如果调用者将左值引用传递给映射类型,它将有条件地返回引用。

 template <typename Map, typename DefVal>
using get_default_return_t = std::conditional_t<std::is_same_v<std::decay_t<DefVal>,
    typename Map::mapped_type> && std::is_lvalue_reference_v<DefVal>,
    const typename Map::mapped_type&, typename Map::mapped_type>;

template <typename Map, typename Key, typename DefVal>
get_default_return_t<Map, DefVal> get_default(const Map& map, const Key& key, DefVal&& defval)
{
    auto i = map.find(key);
    return i != map.end() ? i->second : defval;
}

int main()
{
    std::map<std::string, std::string> map;
    const char cstr[] = "world";
    std::string str = "world";
    auto& ref = get_default(map, "hello", str);
    auto& ref2 = get_default(map, "hello", std::string{"world"}); // fails to compile
    auto& ref3 = get_default(map, "hello", cstr); // fails to compile
    return 0;
}

原文由 MarkB 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题