我试图找出如何在const方法中从map返回值,我偶然发现了在gcc 4.6中map的at()方法。
当我查到这个时,我意识到它是非标准的:
c++ map访问放弃限定符(const)
但是它确实比find()方法少了很多冗长。我想知道c++ 11是否已经纠正了这一点-是在()的映射部分的新标准?
是。std::map
在c++ 11中具有at
成员函数,其规范(23.4.4.3/9)如下:
T& at(const key_type& x); const T& at(const key_type& x) const;
返回:对
*this
中x
对应的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代码的子集略有不同。