How can I get the number of elements in an already array declare by using size function not (sizeof)

281 Views Asked by At

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;
}
2

There are 2 best solutions below

2
Remy Lebeau On

C++17 and later has a std::size() function in the <iterator> header (and various others), e.g.:

#include <iterator>

std::cout << std::size(nums) << "\n";

C++20 adds the std::ssize() function, eg:

std::cout << std::ssize(nums) << "\n";

And just for good measure, another approach would be to use std::array instead of a C-style array, and then you can use its size() method, eg:

#include <array>

std::array<int, 6> nums{10, 20, 30, 40, 20, 50};    

std::cout << nums.size() << "\n";
1
bterwijn On

Or use a template function with a non-type template parameter to deduce the array's size yourself:

#include <iostream>

template<typename T, std::size_t N>
constexpr auto get_size(T(&)[N]) {
    return N;
}

int main()
{
    int nums[] = {10, 20, 30, 40, 20, 50};
    std::cout<<"size: "<< get_size(nums) <<'\n';  // size: 6
}