vector :: operator []以及C ++ STL中的示例
C++vector::operator[]
vector::operator[]是“vector”标头的库函数,用于访问来自vector的指定元素,它接受索引并返回对该元素在指定位置的引用。
注意:要使用向量,请包含<vector>标头。
vector::operator[]的语法
vector::operator[size_type n];
参数:void–这是要访问的元素的位置。
返回值:reference–返回对位置n处元素的引用。
示例
Input: vector<int> vector1{ 1, 2, 3, 4, 5 }; Function call: cout << vector1.[0] << endl; cout << vector1.[1] << endl; Output: 1 2
C++程序演示vector::operator[]的示例
//C++STL程序演示示例 //向量:::operator[] #include <iostream> #include <vector> using namespace std; int main(){ vector<int> v1{ 10, 20, 30, 40, 50 }; //访问元素 cout << "first element : " << v1[0] << endl; cout << "second element: " << v1[1] << endl; cout << "last element : " << v1[v1.size() - 1] << endl; //访问所有元素 cout << "all elements of vector v1..." << endl; for (int i = 0; i < v1.size(); i++) cout << "element at index " << i << " : " << v1[i] << endl; return 0; }
输出结果
first element : 10 second element: 20 last element : 50 all elements of vector v1... element at index 0 : 10 element at index 1 : 20 element at index 2 : 30 element at index 3 : 40 element at index 4 : 50
参考:C++vector::operator[]