C++ 11中地图标准的at()const访问器是什么?

daj*_*daj 8 c++ stl map c++11

我试图弄清楚如何在const方法中从地图返回一个值,我偶然发现了gcc 4.6中map的at()方法.

当我查看它时,我意识到它是非标准的:

C++ map访问丢弃限定符(const)

但它肯定比find()方法简单得多.我想知道C++ 11是否已经纠正了这个问题 - 在新标准的地图部分是()

Jam*_*lis 17

是. 在C++ 11中std::map有一个at成员函数,具有以下规范(23.4.4.3/9):

T&       at(const key_type& x);
const T& at(const key_type& x) const;
Run Code Online (Sandbox Code Playgroud)

返回:到对应于mapped_type的引用x*this.

抛出:out_of_range如果不存在这样的元素,则为类型的异常对象.

复杂性:对数.

但请注意,此成员函数已专门添加到std::map.更一般的关联容器要求不需要它.如果您正在编写需要某种关联容器类型的通用代码,则无法使用此新代码at.相反,您应该继续使用find,这是关联容器概念的一部分,或者编写您自己的非成员帮助程序:

template <typename AssociativeContainer>
typename AssociativeContainer::mapped_type&
get_mapped_value(AssociativeContainer&                          container,
                 typename AssociativeContainer::key_type const& key)
{
    typename AssociativeContainer::iterator it(container.find(key));
    return it != container.end() ? it->second : throw std::out_of_range("key");
}

template <typename AssociativeContainer>
typename AssociativeContainer::mapped_type const&
get_mapped_value(AssociativeContainer const&                    container,
                 typename AssociativeContainer::key_type const& key)
{
    typename AssociativeContainer::const_iterator it(container.find(key));
    return it != container.end() ? it->second : throw std::out_of_range("key");
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您有一个支持右值引用的实现,decltype则不需要两个重载:

template <typename AssociativeContainer, typename Key>
auto get_mapped_value(AssociativeContainer&& container, Key const& key)
    -> decltype(std::declval<AssociativeContainer>().begin()->second)&
{
    auto const it(container.find(key));
    return it != container.end() ? it->second : throw std::out_of_range("key");
}
Run Code Online (Sandbox Code Playgroud)

(或者接近这一点;关于C++ 11的一个有趣的事情是,没有两个编译器具有相同的错误,并且似乎都接受稍微不同的有效和无效的C++ 11代码子集.)