array::operator[ ] in C++ STL
Array classes are generally more efficient, light-weight and reliable than C-style arrays. The introduction of array class from C++11 has offered a better alternative for C-style arrays.
This operator is used to reference the element present at position given inside the operator. It is similar to the at() function, the only difference is that the at() function throws an out-of-range exception when the position is not in the bounds of the size of array, while this operator causes undefined behaviour.
Syntax :
arrayname[position] Parameters : Position of the element to be fetched. Returns : Direct reference to the element at the given position.
Examples:
Input : myarray = {1, 2, 3, 4, 5}
myarray[2]
Output : 3
Input : myarray = {1, 2, 3, 4, 5}
myarray[4]
Output : 5
Errors and Exceptions
1. If the position is not present in the array, it shows undefined behaviour.
2. It has a no exception throw guarantee otherwise.
// CPP program to illustrate // Implementation of [] operator #include <iostream> #include <array> using namespace std; int main() { array<int,5> myarray{ 1, 2, 3, 4, 5 }; cout << myarray[4]; return 0; } |
Output:
5
Application
Given an array of integers, print all the integers present at even positions.
Input :1, 2, 3, 4, 5 Output :1 3 5 Explanation - 1, 3 and 5 are at position 0,2,4 which are even
Algorithm
1. Run a loop till the size of the array.
2. Check if the position is divisible by 2, if yes, print the element at that position.
// CPP program to illustrate // Application of [] operator #include <iostream> #include <array> using namespace std; int main() { array<int,5> myarray{ 1, 2, 3, 4, 5 }; for(int i=0; i<myarray.size(); ++i) { if(i%2==0){ cout<<myarray[i]; cout<<" "; } } return 0; } |
Output:
1 3 5
Recommended Posts:
- Conditional or Ternary Operator (?:) in C/C++
- forward_list insert_after() function in C++ STL
- Count of distinct remainders when N is divided by all the numbers from the range [1, N]
- C++ | asm declaration
- Pointers and References in C++
- Strings in C++ and How to Create them?
- Enum Classes in C++ and Their Advantage over Enum DataType
- Deque vs Vector in C++ STL
- C++ Programming Basics
- Introduction to C++ Programming Language
- ios manipulators noshowpos() function in C++
- ios rdstate() function in C++ with Examples
- ios operator !() function in C++ with Examples
- ios operator() function in C++ with Examples
- ios clear() function in C++ with Examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



