How can I get the number of elements in an already declared array by using the size() function, not sizeof()?
I did that by using the sizeof(), begin(), and end() functions, but how about the size() function??
#include <iostream>
using namespace std;
int main()
{
int nums[] = {10, 20, 30, 40, 20, 50};
// Method 1
cout << sizeof(nums) / sizeof(nums[0]) << "\n";
// Method 2
cout << end(nums) - begin(nums) << "\n";
// Method 3
// ???
return 0;
}
C++17 and later has a
std::size()function in the<iterator>header (and various others), e.g.:C++20 adds the
std::ssize()function, eg:And just for good measure, another approach would be to use
std::arrayinstead of a C-style array, and then you can use itssize()method, eg: