Get the last n items from a vector in C++
Given a vector in C++, we have to get the last n items from it.
For example,
The given vector is
Digits={5,8,9,11,15,20}
Input: n=2
Output: 15 20
To access the last n elements we have to use the size of vector.
Let’s understand this with help of a code.
#include <iostream> #include <vector> using namespace std; int main() { vector<int> Digits {5,8,9,11,15,20}; int length = Digits.size(); // Get number of elements in vector int n=2; for(int i=length-n;i<length;i++) cout<<Digits[i]<<" "; return 0; }
Output: 15 20
Leave a Reply