zoukankan      html  css  js  c++  java
  • C++ Tip: How To Get Array Length | Dev102.com

    http://www.dev102.com/2009/01/12/c-tip-how-to-get-array-length/

    C++ Tip: How To Get Array Length | Dev102.com

    Getting an array length in C# is a trivial task. All we need to so is call the Length property of the Array Class:

    int[] arr = new int[17];
    int arrLength = arr.Length;

    Getting an array length in C++ might be less trivial:

    int arr[17];
    int arrSize = sizeof(arr) / sizeof(int);

    Notice that sizeof(arr) returns the array size in bytes, not its length, so we must remember to divide its result with the size of the array item type (sizeof(int) in the example above).

    I want to show you this nice C++ macro which helps us getting an array length in another and better way:

    template<typename T, int size>
    int GetArrLength(T(&)[size]){return size;}

    This is how to use it:

    template<typename T, int size>
    int GetArrLength(T(&)[size]){return size;}
    
    void main()
    {
        int arr[17];
        int arrSize = GetArrLength(arr);
    }

    aarSize will be equal to 17. Enjoy!

  • 相关阅读:
    yii中通过HTTP post接收
    网络编程
    python 异常处理
    面向对象(2)
    面向对象
    什么是模块精讲
    常用模块二
    各种推导式详解
    匿名函数
    迭代器生成器
  • 原文地址:https://www.cnblogs.com/lexus/p/2847395.html
Copyright © 2011-2022 走看看