如何找出一个数组的长度? [英] How to find out the length of an array?
本文介绍了如何找出一个数组的长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
std::string array[] = { "one", "two", "three" };
我如何找出code中的阵列
的长度?
推荐答案
您可以使用的std ::开始
和的std ::结束
,如果你有C ++ 11的支持:
You can use std::begin
and std::end
, if you have C++11 support.:
int len = std::end(array)-std::begin(array);
// or std::distance(std::begin(array, std::end(array));
另外,你写你自己的模板功能:
Alternatively, you write your own template function:
template< class T, size_t N >
size_t size( const T (&)[N] )
{
return N;
}
size_t len = size(array);
这会工作在C + + 03。如果你是C ++ 11使用它,这将是值得使其成为一个 constexpr
。
This would work in C++03. If you were to use it in C++11, it would be worth making it a constexpr
.
这篇关于如何找出一个数组的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文