array::operator[] with Example in C++ STL

C++ STL | array::operator[]: Here, we are going to learn about the operator [] of Array in C++ STL.
Submitted by IncludeHelp, on February 28, 2019

C++ STL array::operator[]

Operator [] is used to get/set the element of an array in C++ STL, it returns a reference to an element at given index.

Syntax:

    array_name[index];

Parameters: index - position of an element.

Return value: It returns a reference to the element at given index.

Example:

    Input or array declaration:
    array<int,5> values {10, 20, 30, 40, 50};

    Output:
    values[0]	:	10
    values[1]	:	20

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

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

int main()
{
	array<int,5> values {10, 20, 30, 40, 50};

	//printing elements
	cout<<"element at index 0: "<<values[0]<<endl;
	cout<<"element at index 1: "<<values[1]<<endl;
	cout<<"element at index 2: "<<values[2]<<endl;
	cout<<"element at index 3: "<<values[3]<<endl;
	cout<<"element at index 4: "<<values[4]<<endl;

	//changing some of the values
	values[0] = 100;
	values[4] = 500;

	//printing all elements
	cout << "All elements:"<<endl;
	for (int i : values) {
		cout<<i<<" ";
	}
	cout<<endl;

	return 0;
}

Output

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
All elements:
100 20 30 40 500



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.