无法从映射值中获取对。

huangapple go评论52阅读模式
英文:

Can't get pair from map value

问题

我有这个结构

static map<TypeA, pair<reference_wrapper<TypeB>, TypeC>> my_map;

后来,我像这样访问它:

pair<reference_wrapper<TypeB>, TypeC> instance = my_map[type_a_instance];

这个错误触发了:

没有匹配的函数调用 'std::pair<std::reference_wrapper<TypeB>, TypeC>::pair()'
英文:

I have this structure

static map&lt;TypeA, pair&lt;reference_wrapper&lt;TypeB&gt;, TypeC&gt;&gt; my_map;

Later, I access it like this:

pair&lt;reference_wrapper&lt;TypeB&gt;, TypeC&gt; instance = my_map[type_a_instance];

This error triggers:
> no matching function for call to 'std::pair<std::reference_wrapper< TypeB>, TypeC>::pair()'

答案1

得分: 7

map::operator[] 如果没有映射到键的默认构造映射对。由于reference_wrapper的原因,这对于您的映射中的类型是不可能的。请改用find

pair<reference_wrapper<TypeB>, TypeC> instance = 
    my_map.find(type_a_instance)->second;

或者可以使用@Steve Lorimer建议的at

pair<reference_wrapper<TypeB>, TypeC> instance = 
    my_map.at(type_a_instance);

当然,这两个版本都假定可以找到键。find版本在找不到键时会导致未定义行为,at版本会引发std::out_of_range异常。

英文:

map::operator[] must default construct the pair in the map if no mapping for the key exists. That's not possible for the types in your map because of the reference_wrapper. Use find instead.

pair&lt;reference_wrapper&lt;TypeB&gt;, TypeC&gt; instance = 
    my_map.find(type_a_instance)-&gt;second;

Or use at as suggested by @Steve Lorimer

pair&lt;reference_wrapper&lt;TypeB&gt;, TypeC&gt; instance = 
   my_map.at(type_a_instance);

Of course both versions assume that the key can be found. The find version gives you undefined behaviour if the key is not found, the at version gives a std::out_of_range exception.

huangapple
  • 本文由 发表于 2023年3月7日 19:37:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75661486.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定