access last element in vector in c++
To access the last element in a vector in C++, you can use the back()
function. Here are the steps to access the last element in a vector:
Declare a vector variable: Start by declaring a vector variable of the desired type. For example,
std::vector<int> myVector;
declares an empty vector of integers.Add elements to the vector: Use the
push_back()
function to add elements to the vector. For example,myVector.push_back(10);
adds the element 10 to the end of the vector.Access the last element: To access the last element in the vector, use the
back()
function. For example,int lastElement = myVector.back();
assigns the value of the last element in the vector to the variablelastElement
.
Here is an example that demonstrates accessing the last element in a vector:
#include <iostream>
#include <vector>
int main() {
std::vector<int> myVector;
myVector.push_back(10);
myVector.push_back(20);
myVector.push_back(30);
int lastElement = myVector.back();
std::cout << "Last element: " << lastElement << std::endl;
return 0;
}
In this example, the vector myVector
is declared and three elements (10, 20, and 30) are added using the push_back()
function. The last element of the vector, 30, is then accessed using the back()
function and assigned to the variable lastElement
. Finally, the value of lastElement
is printed to the console.
I hope this helps! Let me know if you have any further questions.