Get the length of the array of strings

1.  arithmetic expressions :

#include <iostream>
 
int  main() {
     int  arr[4];
     std::cout <<  sizeof ( arr ) /  sizeof ( arr[0] ) << std::endl;  // 输出4
}

or

#include <iostream>
 
int  main() {
     int  arr[4];
     std::cout <<  sizeof ( arr ) /  sizeof ( *arr ) << std::endl;   // 输出4
}

2.  function template parameters automatically infer:

#include <iostream>
 
template  < typename  T,  size_t  N>
inline  size_t  Count(  T ( & arr )[N] ) {
     return  N;
}
 
int  main() {
     int  arr[4];
     std::cout << Count( arr ) << std::endl;   // 输出4
}

3. Standard C ++ template library:

#include <type_traits>  // 注意包含此头文件.
#include <iostream>
 
int  main() {
     int  arr[4];
     std::cout << std::extent< decltype ( arr ), 0>::value << std::endl;  // 输出4
}

4. The template of the automatic type inference Laid:

include <iostream>
template  < typename  T>
class  ComputeSize;
 
template  < typename  T,  size_t  N>
class  ComputeSize<T[N]> {
public
     static  const  size_t  value = N;
};
 
int  main() { 
     int  arr[4]; 
     std::cout << ComputeSize< decltype ( arr )>::value << std::endl;  // 输出4
}

5.  Visual  C ++ compiler predefined macros:

#include <cstdlib>
#include <iostream>
 
int  main() {
     int  arr[4];
     std::cout << _countof( arr ) << std::endl;   // 输出4.
}

6.  the Boost library :

#include "boost/range.hpp"
#include <iostream>
 
int  main(){   
     int  arr[4];   
     std::cout << boost::size( arr ) << std::endl;  // 输出4
}

The above method is suitable for static arrays, dynamic arrays (new new []) is the number of elements can not be obtained.

 

The above code, you can compile and run their own to see if do not have the above test code or compilers fail to compile, compile and run (the latest version on the following page Visual  C ++ ):

http://webcompiler.cloudapp.net/

 

 

  1.  #include“string.h”

    strlen (a) find a character array size is

  2. sizeof (a) / sizeof (a [0]); This substantially universal

  3.  

Guess you like

Origin www.cnblogs.com/h694879357/p/11762538.html