根据cplusplus.com,std::vector::operator[]有两个重载:
reference operator[] (size_type n);
const_reference operator[] (size_type n) const;
Run Code Online (Sandbox Code Playgroud)
为什么我们需要const该功能的版本?或者,为什么我们不写一个非const函数?
例如,在以下代码中:
std::vector<int> a = {1, 2, 3, 4, 5};
int b = a[1] + a[3]; // Why does it matter if this is const?
Run Code Online (Sandbox Code Playgroud)