To get the first item in a vector in C++, you can use the front
method or directly access the element at index 0.
In this example,
vec
with some elements.front
method of the vector vec
to retrieve the first element.front
method returns a reference to the first element.#include <iostream>
#include <vector>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
int firstItem = vec.front();
std::cout << "First item in the vector: " << firstItem << std::endl;
return 0;
}
First item in the vector: 1
In this example,
vec
with some elements.vec
directly using square brackets []
.#include <iostream>
#include <vector>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
int firstItem = vec[0];
std::cout << "First item in the vector: " << firstItem << std::endl;
return 0;
}
First item in the vector: 1
In this tutorial, we learned How to get First Item in a Vector in C++ language with well detailed examples.