C ++:std :: vector []运算符 [英] C++: std::vector [] operator

查看:75
本文介绍了C ++:std :: vector []运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么std :: vector具有2个运算符 [] 实现?

Why std::vector has 2 operators [] realization ?

reference       operator[]( size_type pos );
const_reference operator[]( size_type pos ) const;

推荐答案

一个用于非常量矢量对象,另一个用于 const 矢量对象.

One for non-const vector object, and the other for const vector object.

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&`
}

如您所见,非const版本允许您使用索引修改向量元素,而 const 版本不允许您修改向量元素.这是这两个版本之间的语义差异.

As you can see, the non-const version lets you modify the vector element using index, while the const version does NOT let you modify the vector elements. That is the semantic difference between these two versions.

有关更多详细说明,请参阅以下常见问题解答:

For more detail explanation, see this FAQ:

希望有帮助.

这篇关于C ++:std :: vector []运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆