2013-04-07 83 views

回答

6

您可以使用std::beginstd::end,如果你有C++ 11的支持:

int len = std::end(array)-std::begin(array); 
// or std::distance(std::begin(array, std::end(array)); 

或者,你寫你自己的模板功能:

template< class T, size_t N > 
size_t size(const T (&)[N]) 
{ 
    return N; 
} 

size_t len = size(array); 

這將在C +工作+03。如果您要在C++ 11中使用它,則值得將它設爲constexpr

+5

或'std :: extent :: value'。 – 2013-04-07 09:59:32

+0

@sftrabbit我甚至沒有想到那個。太好了! – juanchopanza 2013-04-07 10:01:43

+1

@sftrabbit Make ** that **答案並獲得我的+1 – 2013-04-07 10:02:25

4

使用sizeof() - 運算符像

int size = sizeof(array)/sizeof(array[0]); 

或更好,使用std::vector因爲它提供std::vector::size()

int myints[] = {16,2,77,29}; 
std::vector<int> fifth (myints, myints + sizeof(myints)/sizeof(int)); 

Here是文檔。考慮基於範圍的示例。

+0

是否可以使用initializiton定義一個'std :: vector'(就像我在普通數組中的例子)? – NPS 2013-04-07 10:04:46

+1

C++ 11版本初始化器。否則,你可以像你一樣創建一個數組,並將其分配給std :: vector。我在一分鐘後發佈文檔 – 2013-04-07 10:09:59

+0

這個C級別的表達不應該建議沒有解釋[其類型不安全和如何可以補救](http://stackoverflow.com/questions/4810664/how-do-i-use-陣列式-C/7439261#7439261)。 – 2013-04-07 10:12:57

2

像這樣:

int size = sizeof(array)/sizeof(array[0]) 
+0

我知道這個,但我認爲它可能不適用於'std :: string'(由於可變的文本長度)。 – NPS 2013-04-07 10:02:59

+2

這個C級別的表達不應該建議沒有解釋[其類型不安全和如何可以補救](http://stackoverflow.com/questions/4810664/how-do-i-use-arrays-in-c/7439261 #7439261)。 – 2013-04-07 10:18:01

+0

@NPS'sizeof(std :: string)'總是一樣的;它與字符串中存儲了多少個字符沒有任何關係 – 2014-09-27 03:44:16

3

C++ 11提供std::extent它給你沿着陣列的第N維中的元素的數量。默認情況下,N爲0,因此它給出了陣列的長度:

std::extent<decltype(array)>::value 
+0

它是否在編譯時進行所有計算(即編譯後它只是一個數字,不需要額外的計算)? – NPS 2013-04-07 10:13:15

+0

@NPS:是的,你可以看到,它是一種類型 – 2013-04-07 10:15:08

+0

任何使它變短的方法(如宏,但我寧願不使用宏)? – NPS 2013-04-07 10:31:31