Home » C++ STL

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

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL







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.