如何找出一个数组的长度? [英] How to find out the length of an array?

查看:216
本文介绍了如何找出一个数组的长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆