c++ vector size
The std::vector
is a dynamic array in C++ that can grow or shrink in size. It provides a convenient way to store and manipulate collections of elements. The size()
function is a member function of the std::vector
class that returns the number of elements in the vector.
Here are the steps to get the size of a std::vector
in C++:
- Declare and initialize a
std::vector
object:
cpp
std::vector<int> myVector = {1, 2, 3, 4, 5};
In this example, we declare a std::vector
called myVector
and initialize it with five integers.
- Use the
size()
function to get the size of the vector:
cpp
int vectorSize = myVector.size();
The size()
function returns the number of elements in the vector, which is then assigned to the variable vectorSize
.
- Print the size of the vector:
cpp
std::cout << "The size of the vector is: " << vectorSize << std::endl;
This line of code prints the size of the vector to the console.
The output of the above code will be:
The size of the vector is: 5
This indicates that the vector myVector
contains 5 elements.