Home » C++ STL

vector::operator[] with example in C++ STL

C++ STL vector::operator[]: Here, we are going to learn about the operator[] of vector header in C++ STL with example.
Submitted by IncludeHelp, on May 15, 2019

C++ vector::operator[]

vector::operator[] is a library function of "vector" header, it is used to access a specified element from the vector, it accepts an index and returns the reference to the element at the specified position.

Note: To use vector, include <vector> header.

Syntax of vector::operator[]

    vector::operator[size_type n];

Parameter(s): void – It is a position of an element to be accessed.

Return value: reference – It returns a reference to the element at position n.

Example:

    Input:
    vector<int> vector1{ 1, 2, 3, 4, 5 };

    Function call:
    cout << vector1.[0] << endl;
    cout << vector1.[1] << endl;

    Output:
    1
    2

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

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

Output

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

Reference: C++ vector::operator[]






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.