是c++ 11中map标准的at() const访问器
Is the at() const accessor for map standard in C++11?
我试图找出如何在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代码的子集略有不同。
相关文章:
- 如何在类中安全地访问 const 共享数组
- 在只读(即 const)访问器上执行结构化绑定的最佳实践是什么?
- 从 const 对象访问非 const 方法
- 如何在断言中'force' const 访问器的使用?
- 通过 constexpr 中的 'const char *' glvalue 访问字符串文字的值会出错
- 访问函数中 const char *arr[] 的元素
- 如何访问一系列const变量作为const数组
- 隐藏的成员变量不应在仅允许const访问的基类中突变,以便保留分配运算符
- 在函数中使用 const 引用参数访问函数中成员的最佳实践 C++.
- 向 const 字符串参数发送 0 int 文本时的访问冲突
- 如何使用特征访问编译时const值
- 通过const成员变量访问内联函数
- 创建一个 const unique_ptr然后尝试从它 std::move 会给出与您尝试访问复制构造函数相同的错误
- 渲染循环无法访问 Assimp const 场景变量
- 您如何访问 const char **& in C++ 中的数据?
- 如何打印 /访问const void指针的内容
- 跨公共/受保护访问的基于const的函数重载
- 仅授予派生类对基类数据成员/函数的 const 访问权限
- 是c++ 11中map标准的at() const访问器
- 获取对字符串的子字符串的const访问