In C++, you can find the length of an array using the sizeof operator. Here's how you can do it.
In C++, if you're using std::array or std::vector from the Standard Template Library (STL), you can also use the size() method to find the length of the array or vector. Here's how:
Using std::array
:
#include <iostream>
int main() {
int arr[] = {1, 2, 3, 4, 5};
int length = sizeof(arr) / sizeof(arr[0]);
std::cout << "Length of the array: " << length << std::endl;
return 0;
}
Using std::vector
:
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
int length = vec.size();
std::cout << "Length of the vector: " << length << std::endl;
return 0;
}
In this example, sizeof(arr)
gives the total size of the array in bytes, and sizeof(arr[0])
gives the size of one element in the array. Dividing the total size of the array by the size of one element gives the number of elements in the array.
In both cases, the size() method returns the number of elements in the array or vector.