C++ 映射访问丢弃限定符(const)

发布于 2024-07-09 02:13:49 字数 927 浏览 6 评论 0原文

以下代码表示将映射作为 const 传递到 operator[] 方法中会丢弃限定符:

#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 吗?

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

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;
}

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

友欢 2024-07-16 02:13:49

std::map运算符 [] 未声明为 const,并且不能归因于其行为:

T& 运算符[](const Key& key)

返回对映射到与 key 等效的键的值的引用,如果该键不存在则执行插入。

因此,您的函数无法声明为 const,并使用映射的 operator[]

std::mapfind() 功能允许您在不修改地图的情况下查找键。

find() 返回一个 迭代器,或 const_iteratorstd ::pair 包含键 (.first) 和值 (.second)。

在 C++11 中,您还可以使用 at()std::map。 如果元素不存在,该函数会抛出 std::out_of_range 异常,这与 operator [] 不同。

std::map's operator [] is not declared as const, and cannot be due to its behavior:

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.

As a result, your function cannot be declared const, and use the map's operator[].

std::map's find() function allows you to look up a key without modifying the map.

find() returns an iterator, or const_iterator to an std::pair containing both the key (.first) and the value (.second).

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 [].

淡忘如思 2024-07-16 02:13:49

由于 operator[] 没有 const-限定重载,它不能安全地在 const 限定函数中使用。 这可能是因为当前的过载是为了返回和设置键值而构建的。

相反,您可以使用:

VALUE = map.find(KEY)->second;

或者,在 C++11 中,您可以使用 at()< /code>运算符:

VALUE = map.at(KEY);

Since operator[] does not have a const-qualified overload, it cannot be safely used in a const-qualified function. This is probably because the current overload was built with the goal of both returning and setting key values.

Instead, you can use:

VALUE = map.find(KEY)->second;

or, in C++11, you can use the at() operator:

VALUE = map.at(KEY);
尹雨沫 2024-07-16 02:13:49

您不能在 const 的地图上使用 operator[],因为该方法不是 const,因为它允许您修改地图(您可以分配给_map[key])。 尝试改用 find 方法。

You cannot use operator[] on a map that is const as that method is not const as it allows you to modify the map (you can assign to _map[key]). Try using the find method instead.

無心 2024-07-16 02:13:49

一些较新版本的 GCC 头文件(我的机器上为 4.1 和 4.2)具有非标准成员函数 map::at() ,这些函数被声明为 const 并在键不在映射中时抛出 std::out_of_range 。

const mapped_type& at(const key_type& __k) const

从函数注释中的参考来看,这似乎已被建议作为标准库中的新成员函数。

Some newer versions of the GCC headers (4.1 and 4.2 on my machine) have non-standard member functions map::at() which are declared const and throw std::out_of_range if the key is not in the map.

const mapped_type& at(const key_type& __k) const

From a reference in the function's comment, it appears that this has been suggested as a new member function in the standard library.

淡墨 2024-07-16 02:13:49

首先,您不应该使用以 _ 开头的符号,因为它们是语言实现/编译器编写者保留的。 _map 在某人的编译器上很容易成为语法错误,除了你自己,你没有人可以责怪。

如果要使用下划线,请将其放在末尾,而不是开头。 您可能犯了这个错误,因为您看到一些 Microsoft 代码这样做。 请记住,他们编写了自己的编译器,因此他们可能能够逃脱惩罚。 即便如此,这也是一个坏主意。

运算符 [] 不仅返回引用,它实际上在映射中创建条目。 因此,您不仅获得了映射,如果没有映射,您还创建了一个映射。 那不是你的本意。

First, you should not be using symbols beginning with _ because they are reserved to the language implementation/compiler writer. It would be very easy for _map to be a syntax error on someone's compiler, and you would have no one to blame but yourself.

If you want to use an underscore, put it at the end, not the beginning. You probably made this mistake because you saw some Microsoft code doing it. Remember, they write their own compiler, so they may be able to get away with it. Even so, it's a bad idea.

the operator [] not only returns a reference, it actually creates the entry in the map. So you aren't just getting a mapping, if there is none, you are creating one. That's not what you intended.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文