我正在嘗試使用operator[]
in std::map
來使用鍵讀取元素。 但是,當我試圖訪問一個無效的密鑰它是拋出一個異常,我無法趕上使用try
- catch
塊。這裏是我使用的代碼:使用std :: map時無法捕獲未處理的exence :: map
class MapElement
{
public:
int a;
char c;
};
int main()
{
MapElement m1,m2,m3;
map <char ,MapElement*> Mymap;
m1.a =10;m1.c = 'a';
m2.a =20;m2.c ='b';
m3.a =30;m3.c ='c';
map<char,MapElement*>::iterator iter = Mymap.begin();
Mymap.insert(iter , std::pair<int, MapElement*>('1',&m1));
Mymap.insert(iter , std::pair<int, MapElement*>('1',&m2));
cout<<Mymap['1']->a;
try
{
cout<<Mymap['2']->a;
}
catch(exception e)
{
cout<<e.what();
}
catch(...)
{
cout<< "unknown error";
}
}
我該如何處理這個異常?
我試過的std :: out_of_range,但它仍然沒有捕捉異常。我在代碼塊和Visual Studio中都嘗試過。 – kernel
@kernel,工作正常:http://ideone.com/FR4svY – hmjd