gpt4 book ai didi

c++ - std::map 默认值

转载 作者:IT老高 更新时间:2023-10-28 12:06:42 27 4
gpt4 key购买 nike

有没有办法指定当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/

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