C++ map access discards qualifiers (const)(C++ 映射访问丢弃限定符 (const))
问题描述
以下代码表示将映射作为 const 传递到 operator[] 方法会丢弃限定符:
The following code says that passing the map as const into the operator[] method discards qualifiers:
#include <iostream>
#include <map>
#include <string>
using namespace std;
class MapWrapper {
public:
const int &get_value(const int &key) const {
return _map[key];
}
private:
map<int, int> _map;
};
int main() {
MapWrapper mw;
cout << mw.get_value(42) << endl;
return 0;
}
这是因为地图访问时可能发生的分配吗?不能将具有映射访问的函数声明为 const 吗?
Is this because of the possible allocation that occurs on the map access? Can no functions with map accesses be declared const?
MapWrapper.cpp:10: error: passing const std::map<int, int, std::less<int>,
std::allocator<std::pair<const int, int> > > as this argument of
_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&)
[with _Key = int, _Tp = int, _Compare = std::less<int>,
_Alloc = std::allocator<std::pair<const int, int> >] discards qualifiers
推荐答案
std::map 的 operator [] 没有声明为 const,并且不能因为它的行为:
std::map's operator [] is not declared as const, and cannot be due to its behavior:
T&operator[] (const Key& key)
T& operator[] (const Key& key)
返回对映射到与键等效的键的值的引用,如果这样的键不存在,则执行插入.
Returns a reference to the value that is mapped to a key equivalent to key, performing insertion if such key does not already exist.
因此,您的函数不能声明为const,也不能使用地图的operator[].
As a result, your function cannot be declared const, and use the map's operator[].
std::map 的find() 函数允许您在不修改映射的情况下查找键.
std::map's find() function allows you to look up a key without modifying the map.
find() 返回一个iterator 或 const_iterator 到 std::pair 包含键(.first)和值(.second).
find() returns an iterator, or const_iterator to an std::pair containing both the key (.first) and the value (.second).
在 C++11 中,你也可以使用 at() 用于 std::map.如果元素不存在,该函数会抛出一个 std::out_of_range 异常,这与 operator [] 不同.
In C++11, you could also use at() for std::map. If element doesn't exist the function throws a std::out_of_range exception, in contrast to operator [].
这篇关于C++ 映射访问丢弃限定符 (const)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 映射访问丢弃限定符 (const)
基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 这个宏可以转换成函数吗? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
