我正在嘗試撰寫一個函式,當鍵不在 std::map 中時,它會給我一個默認值。在所有情況下,我的默認值都是 numeric_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])’
有人可以幫助我理解錯誤。
提前致謝。
uj5u.com熱心網友回復:
您對模板的限制太多了,因為它要求映射中的鍵與key引數的型別相同。
這失敗了,因為您的地圖存盤std::string但您傳遞了一個字串文字,該字串文字在技術上具有const char[7].
只需制作標題:
template<typename KeyType, typename ValueType,typename T>
ValueType mapDefaultInf(const std::map<KeyType, ValueType> & map, const T& key)
它將允許在map.contains(key)呼叫時進行隱式轉換,如果傳遞給它不兼容的型別,則會失敗并顯示更復雜的錯誤訊息。無論如何,當前的錯誤并不是可讀性的頂峰。
uj5u.com熱心網友回復:
首先你operator[]在函式內部的地圖物件上使用。這永遠不會被允許,因為它是一個非常量函式,并且您已經通過常量參考傳遞了映射。相反,您應該重寫函式實作以使用迭代器:
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"));
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/401081.html
