c++ - std::map 默认值

标签 c++ stdmap

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

最佳答案

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

#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;
}

关于c++ - std::map 默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2333728/

相关文章:

c++ - Boost C++ - 搜索 spirit 符号表

c++ - ATL COM 类注册 .rgs 文件默认值

c++ - 如何设置和使用 std::map<void*, MyClass*>

c++ - 遍历 map<std::string, std::string> 时出错

c++ - 是否可以在 C++ 中将 std::map 与没有任何复制运算符的类一起使用?

c++ - Visual Studio 2017 无法打开源文件 <windows.h>

c++ - 我什么时候需要实现 operator [] ?

c++ - 如何链接GLX?

c++ - std::map 使用迭代器查找距离,程序不会终止