Vector operator[ ] in C++ STL (original) (raw)

Last Updated : 25 Nov, 2024

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 v = {1, 2, 3, 5, 4};

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

return 0;

}

`

**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++:

Table of Content

Syntax of Vector operator[]

v**[i];

**Parameters:

**Return Value:

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 v = {1, 2, 3, 5, 4};

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

return 0;

}

`

Modify Elements in Vector

C++ `

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

int main() { vector 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;

}

`

Out-of-Bound Access Using [] Operator

C++ `

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

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

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

return 0;

}

`

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).