English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ Usage and examples of vector operator[]

C++ Vector (Container)

This function is used to access the specified element.

Syntax

The syntax for the vector (vector) 'v' and position 'pos' is:

v.operator[ ](pos);

Parameter

pos: It defines the position of the element.

Return value

It returns the element at the specified position.

Example1

Let's look at a simple example.

#include<iostream>
#include<vector>
using namespace std;
int main()
{
    vector<string> v{"C","C++","java");
    for(int i = 0; i < v.size(); i++{
        cout << v.operator[](i) << " \t";
    }
    
    return 0;
}

Output:

C C++ java

In this example, use the operator []() function to access each element.

Example2

Let's look at a simple example

#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> v{1,2,3,4,5};
for(int i = 0; i < v.size(); i++)
cout << v.operator[](i) << " \t";
return 0;
}

Output:

1 2 3 4 5

In this example, use the operator[]() function to access each element of the vector (vector) v.

C++ Vector (Container)