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

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

I am trying to write a function, which will give me a default value when the key is not inside a std::map. In all cases will my default value be numerical_limit::infinity().
Hovewer this simple example is not working.

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

Error is:

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

Can someone help me understand the error.

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

Thanks in advance.

>Solution :

First of all you use operator[] on the map object inside the function. That will never be allowed because it is a non-const function and you have passed the map by const reference. Instead you should rewrite the function implementation to use iterators:

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();
}

Second of all you have an ambiguity in the key type. You need to pass in a std::string. Like this:

auto el = mapDefaultInf(map, std::string("alexey"));
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