簡體   English   中英

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

[英]C++: std::vector [] operator

為什么std :: vector有2個operator []實現?

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

一個用於非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元素。 這就是這兩個版本之間的語義差異。

有關詳細說明,請參閱此常見問題解答:

希望有所幫助。

為了實現這種區分:

// 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);

一,以便您可以修改和讀取(非常量)向量

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];

}

兩個重載之一允許您檢索對通過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[]
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM