vector::operator[]

返回对指定位置的矢量元素的引用。

reference operator[](
   size_type Pos
);
const_reference operator[](
   size_typePos
) const;

参数

参数

说明

Pos

矢量元素的位置。

返回值

如果指定的位置大于或等于容器大小,则结果为 undefined。

备注

如果将 operator[] 的返回值分配给 const_reference,则无法修改矢量对象。 如果将 operator[] 的返回值分配给引用,则可以修改矢量对象。

在使用 _SECURE_SCL 1(通过 _ITERATOR_DEBUG_LEVEL 控制)编译时,如果你尝试访问矢量边界以外的元素,则将发生运行时错误。有关详细信息,请参阅经过检查的迭代器

示例

// vector_op_ref.cpp
// compile with: /EHsc
#include <vector>
#include <iostream>

int main( )
{
   using namespace std;   
   vector <int> v1;

   v1.push_back( 10 );
   v1.push_back( 20 );

   int& i = v1[1];
   cout << "The second integer of v1 is " << i << endl;
}

输出

The second integer of v1 is 20

要求

标头:<vector>

命名空间: std

请参见

参考

vector 类

标准模板库