C++11 如何访问函数返回的std::map引用中的值?

C++11 如何访问函数返回的std::map引用中的值?,c++11,dictionary,C++11,Dictionary,我有一个函数,它返回对std::map的常量引用。我想在调用函数的同一语句中立即访问该映射中的值,但显然我无法理解语法 我在这里的话可能不太准确,但让我展示一个小的代码示例,它应该准确地解释我在寻找什么 我的编译器是VS2013更新4 #include <map> struct Foo { Foo() { _foo_map[1] = 3.14; } const std::map<int, double>& get_map() { return _

我有一个函数,它返回对
std::map
的常量引用。我想在调用函数的同一语句中立即访问该映射中的值,但显然我无法理解语法

我在这里的话可能不太准确,但让我展示一个小的代码示例,它应该准确地解释我在寻找什么

我的编译器是VS2013更新4

#include <map>

struct Foo
{
    Foo() { _foo_map[1] = 3.14; }
    const std::map<int, double>& get_map() { return _foo_map; }
    std::map<int, double> _foo_map;
};

void main()
{
    Foo f;

    // I don't like having to have two lines to accomplish this.
    auto m = f.get_map();
    auto d = m[1];

    // This doesn't work.
    // error C2678: binary '[' : no operator found which takes a left-hand operand of type 'const std::map<int,double,std::less<_Kty>,std::allocator<std::pair<const _Kty,_Ty>>>' (or there is no acceptable conversion)
    // auto d2 = f.get_map()[1];

    // This doesn't work.
    // error C2059: syntax error : '['
    // auto d2 = f.get_map().[1];

    // This doesn't work.
    // error C2678: binary '[' : no operator found which takes a left-hand operand of type 'const std::map<int,double,std::less<_Kty>,std::allocator<std::pair<const _Kty,_Ty>>>' (or there is no acceptable conversion)
    // auto& m2 = f.get_map();
    // auto d3 = m2[1];
}
#包括
结构Foo
{
Foo(){u Foo_映射[1]=3.14;}
const std::map&get_map(){return\u foo_map;}
标准::地图_foo_地图;
};
void main()
{
福福;
//我不喜欢用两行代码来完成这个任务。
自动m=f。获取地图();
自动d=m[1];
//这不管用。
//错误C2678:二进制“[”:未找到接受类型为“const std::map”的左侧操作数的运算符(或没有可接受的转换)
//自动d2=f.获取地图()[1];
//这不管用。
//错误C2059:语法错误:'['
//auto d2=f.get_map()[1];
//这不管用。
//错误C2678:二进制“[”:未找到接受类型为“const std::map”的左侧操作数的运算符(或没有可接受的转换)
//自动&m2=f.获取地图();
//自动d3=m2[1];
}
编辑:我现在意识到,读取
auto m=f.get_map();
的行可能应该是
auto&m=f.get_map();
以避免复制映射,当我这样做时,下面的行现在有一个语法错误(与
auto d2
示例相同,不起作用).

没有
const
版本,因为如果找不到键,它将插入新元素

相反,您需要使用:


operator[]
不能在
const
映射上调用。如果键不存在,
operator[]
在返回对映射的引用之前将一个新项插入映射。更改
get\u map()
以返回非const引用,那么您应该能够使用
f.get\u map()[1]
。另一种方法是在
Foo
中添加一个
get_value()
方法:
double get_value(int key){return\u Foo_map[key];}…auto d=f.get_value(1);
@RemyLebeau我希望映射是常量,因此没有人会无意中修改它。我只需要使用
at()访问值吗?是的,您可以使用
at()
const
映射上。
at()
是一个非修改访问器,与
操作符[]
不同。
auto d2 = f.get_map().at(1);