STL中at和[]运算符的区别
STL中at和[]运算符的区别
1. vector
1.1 基础
在vector
中,[]
和at
都会返回一个引用,因此在返回值上是相同的。
但是,at
会额外帮你检查是否越界的问题,如果越界,会抛出一个std::out_of_range
的异常。
std::vector<int> v{1,2,3}; |
1.2 const xxx& operator[]
以int
类型为例。假设有下面这个类,它有两个operator[]
的版本,const
和no const
:
class MyVec |
什么时候调用第一个,什么时候调用第二个?
//no const |
2. map
2.1 []的问题
在map
中,[]
和at
的区别更大。
2.1.1 默认赋值
std::map<char, int> m{{'a', 65}, {'b', 66}, {'c', 67}}; |
2.2.2 不支持const map
const std::map<char, int> m{{'a', 65}, {'b', 66}, {'c', 67}}; |
2.2 合适的用法
cout << m.count('x') ? m['x'] : -1; //OK, but two queries |
发布于