从指针访问映射的索引

Raj*_*war 4 c++ c++11

我目前有这个

struct test
{
 std::map<int, UINT64> ratio;
}
Run Code Online (Sandbox Code Playgroud)

哪里pContext有一个测试指针

int group = 1;
auto a = (*pContext).ratio[group]; <---Error
Run Code Online (Sandbox Code Playgroud)

在上面我得到以下错误

Severity    Code    Description Project File    Line    Suppression State
Error   C2678   binary '[': no operator found which takes a left-hand operand of type 'const std::map<int,UINT64,std::less<int>,std::allocator<std::pair<const int,UINT64>>>' (or there is no acceptable conversion)
Run Code Online (Sandbox Code Playgroud)

关于如何解决这个问题有什么建议吗?

pad*_*ddy 5

您似乎遗漏了重要的细节,但幸运的是,错误消息足以填充这些细节。您的指针不仅仅是“指针”,它显然是一个const指针。

这个问题的原因在于operator[]地图的工作方式。该函数是非常量的(因此不能在 const 对象上调用)。它是非常量的原因是因为它可以修改映射:如果找不到键,它将添加具有默认构造值的键并返回对该值的引用。

要在 const 映射中查找值,您应该使用find

auto it = pContext->ratio.find(group);
if (it != pContext->ratio.end()) {
    std::cout << "Key=" << it->first << " Value=" << it->second << "\n";
}
Run Code Online (Sandbox Code Playgroud)

实际上,您应该更喜欢用这种方法在任何地图上查找值,除非您明确想要添加缺失值或者您确定您的值在地图中。

当然,为了避免一直手动编写这些肮脏的东西,只需将其包装到结构或类似结构上的成员函数中即可。