有没有办法找出一个数组有多少个值?检测是否已经到达数组的末尾也可以工作。
当前回答
而不是使用内置的数组函数aka:
int x[3] = {0, 1, 2};
您应该使用数组类和数组模板。试一试:
#include <array>
array<type_of_the_array, number_of_elements_in_the_array> Name_of_Array = {};
现在如果你想求数组的长度,你所要做的就是使用数组类中的size函数。
Name_of_Array.size();
这应该返回数组中元素的长度。
其他回答
只是一个想法,但只是决定创建一个计数器变量,并将数组大小存储在位置[0]。我删除了函数中的大部分代码,但你会看到退出循环后,prime[0]被分配为'a'的最终值。我尝试使用矢量,但VS Express 2013不太喜欢。还要注意,'a'从1开始,以避免覆盖[0],并在开始时初始化以避免错误。我不是专家,只是想分享一下。
int prime[] = {0};
int primes(int x, int y){
using namespace std; int a = 1;
for (int i = x; i <= y; i++){prime[a] = i; a++; }
prime[0] = a; return 0;
}
如果你指的是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::向量。
避免将类型与sizeof一起使用,因为如果改变数组类型,sizeof(array)/sizeof(char)会突然被破坏。
在visual studio中,你有等效的if sizeof(array)/sizeof(*array)。 你可以输入_countof(array)
#include <iostream>
int main ()
{
using namespace std;
int arr[] = {2, 7, 1, 111};
auto array_length = end(arr) - begin(arr);
cout << "Length of array: " << array_length << endl;
}
还有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