Home »
C++ STL
Different ways to access elements from a Vector in C++ STL
Here, we are going to learn how to access elements from a vector by using different methods in C++ STL?
Submitted by Yash Khandelwal, on April 20, 2019
Different ways to access elements from a vector
1) Using [] operator
Syntax:
vector_name[index]
Parameter: index – is the position in vector.(0-based indexing)
Return Value: The element at that given index.
Example:
vector<int> a;
a.push_back(1);
a.push_back(2);
a.push_back(3);
int p=a[0]; //p=1
int q=a[1]; //q=2
a[n] for any n out of index bound it reflects undefined behavior (depends on compiler).
2) Using function .at(index)
Syntax:
vector_name.at(pos_n)
Parameter: index of desired element
Return value: Returns the referenced element present at input index.
It returns a reference to the element and this function automatically checks whether n is within the range or not. In case of exception it raises out of index range error.
That's the difference between .at() and [] operator does not keep any check for out of the index bounds.
Example:
//On same vector a
int p=a.at(0); //p=1
int q=a.at(1); //q=2
a.at(4) //compilation error
3) front() function
Syntax:
vector_name.front()
Parameter: None
Return value: Return the reference of first element of the vector.
Example:
//On same vector a
int p=a.front() //p=1
Note: Calling this function on an empty vector shows undefined behavior.
4) back() function
Syntax:
vector_name.back()
Parameter: None
Return: Reference of last element.
Example:
//On same vector a
int q=a.back() //q=3
Note: Calling this function on an empty vector shows undefined behavior.
C++ code to demonstrate example of the functions to access vector elements
// C++ program to show
// how to access elements in vector in C++ STL>
#include <vector>
#include <iostream>
using namespace std;
int main( )
{
// declaring vector n
vector<int>n{1,2,3,4,5,6,7,8,9,0};
/* This is how the operator[i]
in c++ works i is the index
which is changing continuously
i.e printing the vector is best example*/
cout <<"Output of operator[]: \n";
for(int i=0; i<n.size(); i++)
cout<<n[i]<<" ";
/* This is how at() works similar
to the operator[] ,
Here it changes the whole vector
*/
cout << "\n\nOutput of at(): \n";
for(int i=0; i<n.size(); i++)
{
n.at(i)=i;
cout<<n.at(i)<<" ";
}
cout << "\n\nOutput of change vector because of at(): \n";
for(int i=0; i<n.size(); i++)
cout<<n[i]<<" ";
/*This is how the front()
works by using that here we are
accessing the front element of vector
*/
cout << "\n\nOutput of front(): \n";
cout<<n.front();
/*This is how the back()
works by using that here we are
accessing the back element of vector
*/
cout << "\n\nOutput of back(): \n";
cout<<n.back();
return 0;
}
Output
Output of operator[]:
1 2 3 4 5 6 7 8 9 0
Output of at():
0 1 2 3 4 5 6 7 8 9
Output of change vector because of at():
0 1 2 3 4 5 6 7 8 9
Output of front():
0
Output of back():
9