有没有办法指定当key不存在时std::map
的operator[]
返回的默认值?
最佳答案
不,没有。最简单的解决方案是编写自己的免费模板函数来执行此操作。比如:
#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/