xxxxxxxxxx
vector<int> vec;
vec.push_back(0);
vec.push_back(1);
int last_element = vec.back();
int also_last_element = vec[vec.size() - 1];
xxxxxxxxxx
vector<int> v;
cout << v[v.size() - 1];
cout << *(v.end() - 1);
cout << *v.rbegin();
// all three of them work
xxxxxxxxxx
#include<iostream>
/*To get the last element of the array we first get the size
of the array by using sizeof(). Unfortunately, this gives
us the size of the array in bytes. To fix this, we divide
the size (in bytes) by the size of the data type in the array.
In our case, this would be int, so we divide sizeof(array)
by sizeof(int). Since arrays start from 0 and not 1 we
subtract one to get the last element.
-yegor*/
int array[5] = { 1, 2, 3, 4, 5 };
printf("Last Element of Array: %d", array[(sizeof(array)/sizeof(int))-1]);
xxxxxxxxxx
// Accessing last element
cout << v.back() << endl;
// modifying last element
v.back() = 100;
xxxxxxxxxx
arr2.rbegin()[1] // rbegin() is reverse order starting at 0 for last element, 1 for second-last
xxxxxxxxxx
#include <iostream>
#include <vector>
int main() {
std::vector<int> nums = {1, 2, 3, 4, 5};
// Method 1: Using negative index
int lastElem1 = nums[nums.size() - 1];
// Method 2: Using back() function
int lastElem2 = nums.back();
std::cout << "Last element (Method 1): " << lastElem1 << std::endl;
std::cout << "Last element (Method 2): " << lastElem2 << std::endl;
return 0;
}