简体   繁体   English

类型没有可行的重载operator []

[英]No viable overloaded operator[] for type

I have defined a type: 我已经定义了一个类型:

typedef unordered_map<string, list<string>> Graph;

I have a key: 我有一把钥匙:

string v = "A12";

When I try to access the list using the key: 当我尝试使用密钥访问列表时:

for (auto w = g[v].begin(); w != g[v].end(); w++)
    {

        ...
    }

g is type Graph , I get the error: g是Graph类型,我得到错误:

No viable overloaded operator[] for type 'const Graph'

How can I fix this issue? 我该如何解决这个问题?

The problem is that g is a const graph& . 问题是g是一个const graph& The indexing operator [] may need to create a new element for the map thus mutating it. 索引operator []可能需要为map创建一个新元素,从而使其发生变异。 That's why you cannot use it on a const graph& (the problem is const ). 这就是为什么你不能在const graph&上使用它(问题是const )。

You can use g.at(key) instead that throws an exception if the key is not present. 如果密钥不存在,您可以使用g.at(key)代替抛出异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM