Open In App

Vector operator[ ] in C++ STL

Last Updated : 25 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, the vector operator [] is used to randomly access or update the elements of vector using their indexes. It is similar to the vector at() function but it doesn’t check whether the given index lies in the vector or not.

Let’s take a look at a simple code example:

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {1, 2, 3, 5, 4};

    // Access the 3rd element using operator[]
    cout << v[2]; 

    return 0;
}

Output
3

Explanation: The third element in the vector v is 3, which is accessed using the operator[].

This article covers the syntax, usage, and common examples of vector operator [] in C++:

Syntax of Vector operator[]

v[i];

Parameters:

  • i: The zero-based index of the element. (position in the sequency starting from 0)

Return Value:

  • Returns a reference to the element at given index.
  • If the given index is out of the bound, then may lead to segmentation fault.

Example of Vector operator[]

The vector operator[] is simple and widely used. The code examples below show how to use it:

Access Elements in Vector

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {1, 2, 3, 5, 4};

    // Access elements using operator[]
    for (size_t i = 0; i < v.size(); i++)
        cout << v[i] << " ";

    return 0;
}

Output
1 2 3 5 4 

Modify Elements in Vector

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {1, 2, 3, 5, 4};

    // Update the 4th element to 10
    v[3] = 10;

    for (size_t i = 0; i < v.size(); i++)
        cout << v[i] << " ";

    return 0;
}

Output
1 2 3 10 4 

Out-of-Bound Access Using [] Operator

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {1, 2, 3, 4, 5};

    // Accessing an element out of range
    cout << v[6] << endl; 

    return 0;
}

Output
132049

The output of this program is undefined and depends on the system or compiler. It may print garbage values or cause a program crash (segmentation fault).



Next Article
Practice Tags :

Similar Reads