用于从const map读取的惯用C ++ [英] Idiomatic C++ for reading from a const map

查看:152
本文介绍了用于从const map读取的惯用C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于 std :: map< std :: string,std :: string>变量,我想这样做:

BOOST_CHECK_EQUAL(variables["a"], "b");

唯一的问题是,在这个上下文中 variables const ,因此 operator [] 将无法工作:

The only problem is, in this context variables is const, so operator[] won't work :(

现在,有几种解决方法:使用 variables.count(a)?变量转储 const find(a) - > second:std :: string()或者甚至做一个函数包装。。这些看起来都不像

Now, there are several workarounds to this; casting away the const, using variables.count("a") ? variables.find("a")->second : std::string() or even making a function wrapping that. None of these seem to me to be as nice as operator[]. What should I do? Is there a standard way of doing this (beautifully)?

编辑: >只是为了说明你没有想要给的答案:不,在C ++中没有方便,美观,标准的方式来做这件事,我必须实现一个支持函数。

Just to state the answer that none of you want to give: No, there is no convenient, beautiful, standard way of doing this in C++. I will have to implement a support function.

推荐答案

template <typename K, typename V>
V get(std::map<K, V> const& map, K const& key)
{
    std::map<K, V>::const_iterator iter(map.find(key));
    return iter != map.end() ? iter->second : V();
}

根据评论改进实施:

template <typename T>
typename T::mapped_type get(T const& map, typename T::key_type const& key)
{
    typename T::const_iterator iter(map.find(key));
    return iter != map.end() ? iter->second : typename T::mapped_type();
}

这篇关于用于从const map读取的惯用C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆