To get the last item in a vector in C++, you can use the back
method provided by the std::vector
class.
In this example,
and
to use the std::vector
class and input/output stream.vec
with a series of integer values using the std::vector
class.back
method on the vector vec
to get a reference to the last element of the vector.back
method returns a reference to the last element in the vector, which we store in a variable named last_item
.std::cout
.#include <vector>
#include <iostream>
int main() {
std::vector<int> vec = {10, 20, 30, 40, 50};
int last_item = vec.back();
std::cout << "The last item is: " << last_item << std::endl;
return 0;
}
The last item is: 50
In this example,
,
, and
to use the std::vector
and std::string
classes and input/output stream.vec
with a series of string values using the std::vector
class.back
method on the vector vec
to get a reference to the last element of the vector.back
method returns a reference to the last element in the vector, which we store in a variable named last_item
.std::cout
.#include <vector>
#include <iostream>
#include <string>
int main() {
std::vector<std::string> vec = {"apple", "banana", "cherry", "date", "elderberry"};
std::string last_item = vec.back();
std::cout << "The last item is: " << last_item << std::endl;
return 0;
}
The last item is: elderberry
In this tutorial, we learned How to get Last Item in a Vector in C++ language with well detailed examples.