有没有办法找出一个数组有多少个值?检测是否已经到达数组的末尾也可以工作。
当前回答
有没有办法找出一个数组有多少个值?
Yes!
尝试sizeof(数组)/ sizeof(阵列[0])
检测是否已经到达数组的末尾也可以工作。
我看不到任何方法,除非你的数组是一个字符数组(即字符串)。
注:在c++中总是使用std::vector。有几个内置函数和一个扩展功能。
其他回答
如果你指的是c风格的数组,那么你可以这样做:
int a[7];
std::cout << "Length of array = " << (sizeof(a)/sizeof(*a)) << std::endl;
这对指针不起作用(即它对以下任何一个都不起作用):
int *p = new int[7];
std::cout << "Length of array = " << (sizeof(p)/sizeof(*p)) << std::endl;
or:
void func(int *p)
{
std::cout << "Length of array = " << (sizeof(p)/sizeof(*p)) << std::endl;
}
int a[7];
func(a);
在c++中,如果你想要这种行为,那么你应该使用容器类;可能std::向量。
有没有办法找出一个数组有多少个值?
Yes!
尝试sizeof(数组)/ sizeof(阵列[0])
检测是否已经到达数组的末尾也可以工作。
我看不到任何方法,除非你的数组是一个字符数组(即字符串)。
注:在c++中总是使用std::vector。有几个内置函数和一个扩展功能。
我个人建议(如果你因为任何原因无法使用专门的函数)首先扩展数组类型的兼容性,超出你通常使用它的范围(如果你存储的值≥0:
unsigned int x[] -> int x[]
你会让数组的元素比你需要的要大。对于最后一个元素,你可以放置一些类型,包括在扩展类型说明符中,但你通常不会使用,例如,使用前面的例子,最后一个元素将是-1。这使您能够(通过使用for循环)找到数组的最后一个元素。
这是一个非常古老和传奇的问题,已经有很多惊人的答案。但是随着时间的推移,新的功能被添加到语言中,所以我们需要根据可用的新功能不断更新。
我只是注意到还没有人提到c++ 20。所以想写答案。
C + + 20
在c++ 20中,标准库中增加了一种新的更好的方法来查找数组的长度,即std:ssize()。这个函数返回一个带符号的值。
#include <iostream>
int main() {
int arr[] = {1, 2, 3};
std::cout << std::ssize(arr);
return 0;
}
C++17
在c++ 17中,(当时)有一个更好的方法来实现same,即在iterator中定义std::size()。
#include <iostream>
#include <iterator> // required for std::size
int main(){
int arr[] = {1, 2, 3};
std::cout << "Size is " << std::size(arr);
return 0;
}
附注:这个方法也适用于矢量。
Old
这种传统的方法已经在许多其他的答案中提到过。
#include <iostream>
int main() {
int array[] = { 1, 2, 3 };
std::cout << sizeof(array) / sizeof(array[0]);
return 0;
}
仅供参考,如果你想知道为什么这种方法不工作时,数组传递给另一个函数。原因是,
在c++中,数组不是按值传递的,而是传递指向数组的指针。在某些情况下,传递整个数组可能是昂贵的操作。你可以通过将数组传递给某个函数来测试这一点,并对那里的数组进行一些更改,然后再次在main中打印数组。你会得到更新的结果。
正如你已经知道的,sizeof()函数给出了字节数,所以在其他函数中,它将返回分配给指针的字节数,而不是整个数组。所以这种方法行不通。
但我相信你能根据你的要求找到一个好办法。
快乐的编码。
还有TR1/ c++ 11/ c++ 17方式(参见Coliru Live):
const std::string s[3] = { "1"s, "2"s, "3"s };
constexpr auto n = std::extent< decltype(s) >::value; // From <type_traits>
constexpr auto n2 = std::extent_v< decltype(s) >; // C++17 shorthand
const auto a = std::array{ "1"s, "2"s, "3"s }; // C++17 class template arg deduction -- http://en.cppreference.com/w/cpp/language/class_template_argument_deduction
constexpr auto size = std::tuple_size_v< decltype(a) >;
std::cout << n << " " << n2 << " " << size << "\n"; // Prints 3 3 3