有没有办法找出一个数组有多少个值?检测是否已经到达数组的末尾也可以工作。
当前回答
您可以使用sizeof()操作符,该操作符用于相同的目的。
请参阅下面的示例代码
#include <iostream>
using namespace std;
int main() {
int arr[] = {10,20,30,40,50,60};
int arrSize = sizeof(arr)/sizeof(arr[0]);
cout << "The size of the array is: " << arrSize;
return 0;
}
其他回答
最常见的原因之一是,您希望将数组传递给函数,而不必为其大小传递另一个参数。您通常也希望数组大小是动态的。该数组可能包含对象,而不是原语,而且对象可能很复杂,因此size_of()是计算计数的不安全选项。
正如其他人建议的那样,考虑使用std::vector或list等来代替原始数组。然而,在旧的编译器上,您仍然不能通过简单地这样做得到您可能想要的最终解决方案,因为填充容器需要大量丑陋的push_back()行。如果你像我一样,想要一个包含匿名对象的单行解决方案。
如果你使用STL容器替代原始数组,那么这篇SO文章可能会对你有用,让你知道如何初始化它: 用硬编码的元素初始化std::vector最简单的方法是什么?
下面是我使用的一个方法,它将在编译器和平台上普遍工作:
为对象集合创建一个结构体或类作为容器。为<<定义运算符重载函数。
class MyObject;
struct MyObjectList
{
std::list<MyObject> objects;
MyObjectList& operator<<( const MyObject o )
{
objects.push_back( o );
return *this;
}
};
你可以创建以你的结构体作为参数的函数,例如:
someFunc( MyObjectList &objects );
然后,你可以调用这个函数,像这样:
someFunc( MyObjectList() << MyObject(1) << MyObject(2) << MyObject(3) );
这样,您就可以在一行代码中构建并将动态大小的对象集合传递给函数!
如果你指的是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::向量。
vector有一个size()方法,该方法返回vector中元素的数量。
(是的,这是半开玩笑的回答)
下面是谷歌Protobuf中ArraySize的一个实现。
#define GOOGLE_ARRAYSIZE(a) \
((sizeof(a) / sizeof(*(a))) / static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))))
// test codes...
char* ptr[] = { "you", "are", "here" };
int testarr[] = {1, 2, 3, 4};
cout << GOOGLE_ARRAYSIZE(testarr) << endl;
cout << GOOGLE_ARRAYSIZE(ptr) << endl;
ARRAYSIZE(arr) works by inspecting sizeof(arr) (the # of bytes in the array) and sizeof(*(arr)) (the # of bytes in one array element). If the former is divisible by the latter, perhaps arr is indeed an array, in which case the division result is the # of elements in the array. Otherwise, arr cannot possibly be an array, and we generate a compiler error to prevent the code from compiling. Since the size of bool is implementation-defined, we need to cast !(sizeof(a) & sizeof(*(a))) to size_t in order to ensure the final result has type size_t. This macro is not perfect as it wrongfully accepts certain pointers, namely where the pointer size is divisible by the pointee size. Since all our code has to go through a 32-bit compiler, where a pointer is 4 bytes, this means all pointers to a type whose size is 3 or greater than 4 will be (righteously) rejected.
而不是使用内置的数组函数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();
这应该返回数组中元素的长度。