相关疑难解决方法(0)

C++ const map元素访问

我试图使用operator []访问const C++映射中的元素,但此方法失败.我也尝试用"at()"来做同样的事情.这次工作.但是,我找不到任何关于使用"at()"来访问const C++映射中的元素的引用."at()"是C++地图中新添加的函数吗?我在哪里可以找到更多关于此的信息?非常感谢你!

一个例子如下:

#include <iostream>
#include <map>

using namespace std;

int main()
{
        map<int, char> A;
        A[1] = 'b';
        A[3] = 'c';

        const map<int, char> B = A;

        cout << B.at(3) << endl; // it works
        cout << B[3] << endl;  // it does not work

}
Run Code Online (Sandbox Code Playgroud)

对于使用"B [3]",它在编译期间返回以下错误:

t01.cpp:14:错误:将'const std :: map,std :: allocator >>'传递为'_Tp&std :: map <_Key,_Tp,_Compare,_Alloc> :: operator []的'this'参数( const _Key&)[with _Key = int,_Tp = char,_Compare = std :: less,_Alloc = std :: allocator>]'丢弃限定符

使用的编译器是g …

c++ stl const map

88
推荐指数
2
解决办法
5万
查看次数

在const方法中使用operator []和map

说我有这样的方法

int someclass::somemethod(const std::string &name) const
{
       std::string a = mymap["a"];
       ..... 
}
Run Code Online (Sandbox Code Playgroud)

mymap的位置

std::map<std::string,std::string> 
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误

Error   1   error C2678: binary '[' : no operator found which takes a left-hand operand of type 'const std::map<std::string, std::string>   ' (or there is no acceptable conversion)    
Run Code Online (Sandbox Code Playgroud)

关于如何获取密钥值的任何建议??

c++

0
推荐指数
2
解决办法
200
查看次数

标签 统计

c++ ×2

const ×1

map ×1

stl ×1