以下代码表示将映射作为 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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!