C++獲取數組的長度


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
請按任意鍵繼續. . .


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM