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

时间:2013-02-13 18:38:46

标签: c++ stl std stdvector

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

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

4 个答案:

答案 0 :(得分:9)

一个用于非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&`
}

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

有关详细说明,请参阅此常见问题解答:

希望有所帮助。

答案 1 :(得分:1)

使这种区分成为可能:

// const vector object, cannot be modified
// const operator[] allows for this
int get_value(const std::vector<int>& vec, size_t index)
{
   return vec[index];
}

// non-const vector object can be modified
// non-const operator[] allows for this
void set_value(std::vector<int>& vec, size_t index, int val)
{
   vec[index] = value;
}

std::vector<int> values;
values.push_back(10);
values.push_back(20);

set_value(values, 0, 50);
get_value(values, 0);

答案 2 :(得分:1)

一个可以修改和读取(非常量)向量

void foo( std::vector<int>& vector )
{
    // reference operator[]( size_type );
    int old = vector[0];
    vector[0] = 42;
}

一个可以从const向量中读取

void foo( std::vector<int> const& vector )
{
    //const_reference operator[]( size_type ) const;
    int i = vector[0];

}

答案 3 :(得分:0)

两个重载中的一个允许您检索对通过const变量访问的向量元素的const引用。另一个允许您获取对通过非const变量访问的向量元素的非const引用。

如果您没有const版本,则不允许编译以下内容:

void f(vector<int> const& v)
{
    cout << v[0]; // Invokes the const version of operator []
}

在下面的示例中,将调用非const版本,该版本返回对数组中第一个元素的非const引用,并允许(例如)为其分配新值:

void f(vector<int>& v)
{
    v[0] = 1; // Invokes the non-const version of operator[]
}
相关问题