[英]How to find out the length of an array?
std::string array[] = { "one", "two", "three" };
如何在代碼中找出array
的長度?
如果您有C ++ 11支持,則可以使用std::begin
和std::end
。
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
。
使用sizeof()
operator像
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) );
這是文檔。 考慮基於范圍的示例。
C ++ 11提供了std::extent
,它為您提供了數組第N
個維度上的元素數量。 默認情況下, N
為0,因此它為您提供了數組的長度:
std::extent<decltype(array)>::value
像這樣:
int size = sizeof(array)/sizeof(array[0])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.