Get the array length in C + +

Source: Internet
Author: User
Tags array length


A function that directly obtains the length of an array is not available in C + +

One of the ways to get the array length is by using sizeof (array)/sizeof (Array[0]).

It is customary in C to define it as a macro when used, such as:

#define Get_array_len (array,len) {LEN = (sizeof (ARRAY)/sizeof (array[0));}

In C + +, you can use template technology to define a function, such as:

Template <class t>
int Getarraylen (t& array)
{
Return (sizeof (array)/sizeof (array[0));
}

This allows you to use this macro or this function to get the length of the array for some simple arrays.

C Language Usage:
#define Get_array_len (array,len) {LEN = (sizeof (ARRAY)/sizeof (array[0));}
Define a macro with parameters to store the length of the array in the variable len
int main ()
{
Char a[] = {' 1 ', ' 2 ', ' 3 ', ' 4 '};
int Len;

Get_array_len (A,len)
Call a predefined macro to get the length of array A and store it in the variable len
}


C + + Usage:
int main ()
{
Char a[] = {' 1 ', ' 2 ', ' 3 '};
cout << Getarraylen (a) << Endl;
}

Get the array length in C + +

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.