C++ 数组的长度:

#include<iostream>
using namespace std;

template<class T>

int length(T& arr)
{
    //cout << sizeof(arr[0]) << endl;
    //cout << sizeof(arr) << endl;
    return sizeof(arr) / sizeof(arr[0]);
}

int main()
{
    int arr[] = { 1,5,9,10,9,2 };
    // 方法一
    cout << "数组的长度为:" << length(arr) << endl;
    // 方法二
    //cout << end(arr) << endl;
    //cout << begin(arr) << endl;
    cout << "数组的长度为:" << end(arr)-begin(arr) << endl;
    system("pause");
    return 0;
}

输出结果为:

数组的长度为:6
数组的长度为:6

对于字符串数组,可以用 strlen() 函数来获取字符串数组的长度。

相关文章:

  • 2021-11-24
  • 2022-12-23
  • 2022-03-08
  • 2021-05-24
  • 2021-06-09
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-07-24
  • 2021-08-13
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案