To get the length of a vector in C++, you can use the size
method of the std::vector
class from the Standard Template Library (STL).
In this example,
header to use the std::vector
class and the
header to use input/output streams.num_vector
that holds integers using the std::vector
declaration.num_vector
with a set of numeric values using an initializer list {10, 20, 30, 40, 50}
.size
method on num_vector
to get the number of elements in the vector. The size
method returns the length of the vector as a size_t
value.size
method to a variable named num_vector_length
.std::cout
to display the value of num_vector_length
on the console.#include <vector>
#include <iostream>
int main() {
std::vector<int> num_vector = {10, 20, 30, 40, 50};
std::size_t num_vector_length = num_vector.size();
std::cout << "Length of numeric vector: " << num_vector_length << std::endl;
return 0;
}
Length of numeric vector: 5
In this example,
header to use the std::vector
class and the
header to use input/output streams.str_vector
that holds strings using the std::vector
declaration.str_vector
with a set of string values using an initializer list {"apple", "banana", "cherry"}
.size
method on str_vector
to get the number of elements in the vector. The size
method returns the length of the vector as a size_t
value.size
method to a variable named str_vector_length
.std::cout
to display the value of str_vector_length
on the console.#include <vector>
#include <iostream>
int main() {
std::vector<std::string> str_vector = {"apple", "banana", "cherry"};
std::size_t str_vector_length = str_vector.size();
std::cout << "Length of string vector: " << str_vector_length << std::endl;
return 0;
}
Length of string vector: 3
In this tutorial, we learned How to Get Length of a Vector in C++ language with well detailed examples.