How to find out the length of an array?

感情迁移 提交于 2019-12-23 03:14:48

问题


std::string array[] = { "one", "two", "three" };

How do I find out the length of the array in code?


回答1:


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);

This would work in C++03. If you were to use it in C++11, it would be worth making it a constexpr.




回答2:


Use the sizeof()-operator like in

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

or better, use std::vector because it offers std::vector::size().

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

Here is the doc. Consider the range-based example.




回答3:


C++11 provides std::extent which gives you the number of elements along the Nth dimension of an array. By default, N is 0, so it gives you the length of the array:

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



回答4:


Like this:

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


来源:https://stackoverflow.com/questions/15861115/how-to-find-out-the-length-of-an-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!