目录

vector::operator[]

描述 (Description)

C ++函数std::vector::operator[]返回对位置n处的元素的引用。

声明 (Declaration)

以下是std :: vector :: operator []函数形式std :: vector标头的声明。

C++98

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

参数 (Parameters)

n - 元素在容器中的位置。

返回值

返回对位置n处的元素的引用。

异常 (Exceptions)

这个成员函数永远不会抛出异常。 如果n不是有效索引,则行为未定义。

时间复杂

常数即O(1)

例子 (Example)

以下示例显示了std :: vector :: operator []函数的用法。

#include <iostream>
#include <vector>
using namespace std;
int main(void) {   
   vector<int> v = {1, 2, 3, 4, 5};
   for (int i = 0; i < v.size(); ++i)
      cout << v[i] << endl;
   return 0;
}

让我们编译并运行上面的程序,这将产生以下结果 -

1
2
3
4
5
↑回到顶部↑
WIKI教程 @2018