gpt4 book ai didi

c++ - 如何创建容器模板(例如 std::map)?

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:58:59 27 4
gpt4 key购买 nike

例如,我有一个简单的工作代码

template <typename T, typename VALUE>
VALUE mapAt(T key)
{
std::map<T, VALUE>::const_iterator item_i(MyMap.find(key))
, end_i(MyMap.end());
if (item_i == end_i)
{
throw std::exception("No such key!");
}

return (*item_i).second;
}

问题:是否可以不使用 std::map 而使用不同的容器(例如 std::map, std::multimap, ...),像这样:

template <class Container, typename T, typename VALUE>
VALUE mapAt(Container& MyMap, T key)
{
Container<T, VALUE>::const_iterator item_i(MyMap.find(key))
, end_i(MyMap.end());
/* ... */
}

问题:当我尝试使用它时,例如:

std::map<int, char> my_map;
char ch = mapAt<std::map<int, char>(), int, char>(my_map, 123); // C2664 error

编译器给我一个错误:

main.cpp(119) : error C2664: 'mapAt' : cannot convert parameter 1 from 'std::map<_Kty,_Ty>' to 'std::map<_Kty,Ty> (_cdecl &)' 1>
with 1> [ 1>
_Kty=int, 1> _Ty=char 1> ] 1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

最佳答案

你可以这样写:

template <class Container>
typename Container::mapped_type mapAt(Container& MyMap, typename const Container::key_type& key)
{
typename Container::const_iterator iter = MyMap.find(key);
return iter->second;
}

int main()
{
std::map<int, char> my_map;
char ch = mapAt(my_map, 123);
}

关于c++ - 如何创建容器模板(例如 std::map)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5336498/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com