gpt4 book ai didi

c++ - C++11 中 map 标准的 at() const 访问器是什么?

转载 作者:可可西里 更新时间:2023-11-01 17:17:31 27 4
gpt4 key购买 nike

我试图找出如何在 const 方法中从 map 返回一个值,我偶然发现了 gcc 4.6 中 map 的 at() 方法。

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

C++ map access discards qualifiers (const)

但它确实比 find() 方法要简洁得多。我想知道 C++11 是否已纠正此问题 - at() for map 是新标准的一部分吗?

最佳答案

是的。 std::map 在 C++11 中有一个 at 成员函数,其规范如下 (23.4.4.3/9):

T&       at(const key_type& x);
const T& at(const key_type& x) const;

Returns: A reference to the mapped_type corresponding to x in *this.

Throws: An exception object of type out_of_range if no such element is present.

Complexity: logarithmic.

但是请注意,此成员函数已专门添加到 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 代码子集。)

关于c++ - C++11 中 map 标准的 at() const 访问器是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7357331/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com