T& at(const key_type& x);
const T& at(const key_type& x) const;
返回值:返回与x
对应的*this
中的mapped_type
的引用。
抛出异常:如果不存在这样的元素,则抛出类型为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");
}
如果你有一个支持右值引用和 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");
}
(或类似的内容;C ++ 11的有趣之处在于,没有两个编译器有相同的错误,并且所有编译器似乎都接受略微不同的有效 - 和无效的 - C ++ 11代码子集。)
UniqueAssociativeContainer
会是一个更好的模板参数名称(UniqueAssociativeContainerOrUniqueUnorderedAssociativeContainer
太笨重了:-O)。关键是有些容器满足容器概念的要求,而且应该在通用代码中与C++标准库容器互换使用。依赖新的at
的代码无法利用这些其他容器。 - James McNellis