Ser*_*kyi 6 c++ stl std stdvector
为什么std :: vector有2个运算符[] 实现?
reference operator[]( size_type pos );
const_reference operator[]( size_type pos ) const;
Run Code Online (Sandbox Code Playgroud)
一个用于非const矢量对象,另一个用于const矢量对象.
void f(std::vector<int> & v1, std::vector<int> const & v2)
{
//v1 is non-const vector
//v2 is const vector
auto & x1 = v1[0]; //invokes the non-const version
auto & x2 = v2[0]; //invokes the const version
v1[0] = 10; //okay : non-const version can modify the object
v2[0] = 10; //compilation error : const version cannot modify
x1 = 10; //okay : x1 is inferred to be `int&`
x2 = 10; //error: x2 is inferred to be `int const&`
}
Run Code Online (Sandbox Code Playgroud)
如您所见,非const版本允许您使用索引修改矢量元素,而const版本不允许您修改矢量元素.这就是这两个版本之间的语义差异.
有关详细说明,请参阅此常见问题解答:
希望有所帮助.