我有一个函数返回对std::map
的const引用。我想在调用函数的同一语句中立即访问该映射中的值,但显然我无法弄清楚语法...
我在这里的说法可能不准确,但让我展示一个小代码示例,它应该能够准确地解释我在寻找什么。
我的编译器是VS2013 Update 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];
}
编辑:我现在意识到读取auto m = f.get_map();
的行应该是auto& m = f.get_map();
以避免复制地图,当我这样做时,现在跟随的行有一个语法错误(与auto d2
示例不起作用。)
答案 0 :(得分:2)