To get the length of a list in C++, you can use the size()
method of the std::list
class.
In this example,
numbers
with integer values using std::list
.size()
method of the list object numbers
to get the number of elements in the list.size()
method returns the number of elements in the list.#include <iostream>
#include <list>
int main() {
std::list<int> numbers = {1, 2, 3, 4, 5};
std::cout << "Length of the list is: " << numbers.size() << std::endl;
return 0;
}
Length of the list is: 5
In this example,
fruits
with string values using std::list
.size()
method of the list object fruits
to get the number of elements in the list.size()
method returns the number of elements in the list.#include <iostream>
#include <list>
#include <string>
int main() {
std::list<std::string> fruits = {"apple", "banana", "cherry"};
std::cout << "Length of the list is: " << fruits.size() << std::endl;
return 0;
}
Length of the list is: 3
In this tutorial, we learned How to Get Length of a List in C++ language with well detailed examples.