我試着寫我自己的函數這一點,但我得到錯誤的結果如何在C++中獲取數組的長度?
#include <iostream>
using namespace std;
template<typename T>
int array_length(T v[]) {
return (sizeof v)/sizeof(T);
}
int main() {
int v[] = {1, 2, 3, 4};
cout << array_length(v) << endl;
return 0;
}
https://gist.github.com/3959946查看上一個函數。 –
http://stackoverflow.com/questions/3368883/how-does-this-size-of-array-template-function-work – relaxxx
@ R.MartinhoFernandes:即使編譯器知道大小,該函數將在運行時給出大小在編譯時本身。因此,我不會說這是一個很好的實施。 – Nawaz