使用 std::map 时提供默认值的函数

Function to provide a default value when working with std::map

我正在尝试编写一个函数,当键不在 std::map 内时,它会给我一个默认值。在所有情况下,我的默认值都是 numerical_limit::infinity()。 然而,这个简单的例子不起作用。

#include <iostream>
#include <map>
#include <limits>

template<typename KeyType, typename ValueType>
ValueType mapDefaultInf(const std::map<KeyType, ValueType> & map, const KeyType & key)
{
    if(!map.contains(key))
    {
        return std::numeric_limits<ValueType>::infinity();
    }
    else
    {
        return map[key];
    }
}

int main()
{
    std::map<std::string, int> map;
    auto el = mapDefaultInf(map, "alexey");
    std::cout << el << std::endl;

    return 0;
}

错误是:

main.cpp:29:42: error: no matching function for call to ‘mapDefaultInf(std::map, int>&, const char [7])’

谁能帮我理解这个错误。

提前致谢。

您对模板的限制太多,因为它要求映射中的键与 key 参数的类型相同。

这失败了,因为你的地图存储了 std::string 但你传递了一个字符串文字,它在技术上具有 const char[7].

的类型

只需header:

template<typename KeyType, typename ValueType,typename T>
ValueType mapDefaultInf(const std::map<KeyType, ValueType> & map, const T& key)

它将允许在 map.contains(key) 调用时进行隐式转换,如果您向它传递不兼容的类型,它只会失败并显示更复杂的错误消息。无论如何,当前的错误并不是可读性的顶峰。

首先,您在函数内的地图对象上使用 operator[]。这将永远不会被允许,因为它是一个非常量函数,并且您已经通过 const 引用传递了地图。相反,您应该重写函数实现以使用迭代器:

template<typename KeyType, typename ValueType>
ValueType mapDefaultInf(const std::map<KeyType, ValueType> & map, const KeyType & key)
{
    const auto it = map.find(key);
    return it != map.end() ?  it->second : std::numeric_limits<ValueType>::infinity();
}

其次,您的密钥类型不明确。你需要传入一个std::string。像这样:

auto el = mapDefaultInf(map, std::string("alexey"));