std::vectorv; v.push_back(1); int b = v[3]; int c = v.at(3);
程序执行到v[3]时:
程序执行到at(3)时:
一个是直接崩溃,一个抛出异常,抛出异常可以捕获异常:
std::vectormapv; v.push_back(1); //int b = v[3]; try { int c = v.at(3); } catch (const std::out_of_range& e) { cout << e.what() << endl; }
std::mapm; m.insert(std::pair (1, 2)); int a = m.at(11); int c = m[11];
程序执行到at(11)时:和vector现象一样,抛出异常
程序执行到[11]时是正常执行,可以看看执行前后map的size的变化:
std::mapm; m.insert(std::pair (1, 2)); cout << "执行前size:"<
可以看到使用[]访问一个不存在的key是向map中插入元素


![[]和at的区别 []和at的区别](http://www.mshxw.com/aiimages/31/290421.png)
