當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C++ vector::operator[]用法及代碼示例


C++ 向量::運算符[]

vector::operator[] 是 "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

演示vector::operator[]示例的C++程序

//C++ STL program to demonstrate example of
//vector::operator[]

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<int> v1{ 10, 20, 30, 40, 50 };

    //accessing elements
    cout << "first element:" << v1[0] << endl;
    cout << "second element:" << v1[1] << endl;
    cout << "last element :" << v1[v1.size() - 1] << endl;

    //accessing all elemenets
    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[]



相關用法


注:本文由純淨天空篩選整理自 vector::operator[] with example in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。