有没有办法找出一个数组有多少个值?检测是否已经到达数组的末尾也可以工作。


如果你指的是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。有几个内置函数和一个扩展功能。


执行sizeof myArray将得到分配给该数组的总字节数。然后,您可以通过除以数组中一个元素的大小来找出数组中的元素数量:sizeof myArray[0]

所以,你会得到这样的东西:

size_t LengthOfArray = sizeof myArray / sizeof myArray[0];

由于sizeof产生size_t,结果LengthOfArray也将是这种类型。


vector有一个size()方法,该方法返回vector中元素的数量。

(是的,这是半开玩笑的回答)


正如其他人所说,您可以使用sizeof(arr)/sizeof(*arr),但这将为非数组的指针类型提供错误的答案。

template<class T, size_t N>
constexpr size_t size(T (&)[N]) { return N; }

这具有对非数组类型编译失败的良好属性(Visual Studio有_countof可以做到这一点)。constexpr使它成为编译时表达式,因此它没有任何宏的缺点(至少我不知道)。

你也可以考虑使用c++ 11中的std::array,它公开了它的长度,而不增加C原生数组的开销。

c++ 17在<iterator>头文件中有std::size(),它具有相同的功能,也适用于STL容器(感谢@Jon C)。


只是一个想法,但只是决定创建一个计数器变量,并将数组大小存储在位置[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;
}

而不是使用内置的数组函数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();

这应该返回数组中元素的长度。


假设在页面顶部声明了一个全局数组

int global[] = { 1, 2, 3, 4 };

要找出数组中有多少个元素(在c++中),输入以下代码:

sizeof(global) / 4;

sizeof(NAME_OF_ARRAY) / 4将返回给定数组名的元素数量。


还有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

#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;
}

下面是谷歌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.


使用泛型的一个好的解决方案:

template <typename T,unsigned S>
inline unsigned arraysize(const T (&v)[S]) { return S; }

然后简单地调用arraysize(_Array);来获取数组的长度。


在c++中,使用std::array类来声明数组,可以很容易地找到数组的大小以及最后一个元素。

#include<iostream>
#include<array>
int main()
{
    std::array<int,3> arr;

    //To find the size of the array
    std::cout<<arr.size()<<std::endl;

    //Accessing the last element
    auto it=arr.end();
    std::cout<<arr.back()<<"\t"<<arr[arr.size()-1]<<"\t"<<*(--it);

    return 0;
}

事实上,数组类有很多其他函数,让我们使用数组作为标准容器。 参考1到c++ std::array类 引用2到std::array类 参考文献中的例子很有帮助。


最常见的原因之一是,您希望将数组传递给函数,而不必为其大小传递另一个参数。您通常也希望数组大小是动态的。该数组可能包含对象,而不是原语,而且对象可能很复杂,因此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) );

这样,您就可以在一行代码中构建并将动态大小的对象集合传递给函数!


对于旧的g++编译器,您可以这样做

template <class T, size_t N>
char (&helper(T (&)[N]))[N];

#define arraysize(array) (sizeof(helper(array)))

int main() {
    int a[10];
    std::cout << arraysize(a) << std::endl;
    return 0;
}

避免将类型与sizeof一起使用,因为如果改变数组类型,sizeof(array)/sizeof(char)会突然被破坏。

在visual studio中,你有等效的if sizeof(array)/sizeof(*array)。 你可以输入_countof(array)


从c++ 11开始,引入了一些新的模板来帮助减少处理数组长度时的痛苦。它们都定义在header <type_traits>中。

std::rank<T>::value If T is an array type, provides the member constant value equal to the number of dimensions of the array. For any other type, value is 0. std::extent<T, N>::value If T is an array type, provides the member constant value equal to the number of elements along the Nth dimension of the array, if N is in [0, std::rank<T>::value). For any other type, or if T is array of unknown bound along its first dimension and N is 0, value is 0. std::remove_extent<T>::type If T is an array of some type X, provides the member typedef type equal to X, otherwise type is T. Note that if T is a multidimensional array, only the first dimension is removed. std::remove_all_extents<T>::type If T is a multidimensional array of some type X, provides the member typedef type equal to X, otherwise type is T.

要获得多维数组的任何维度上的长度,可以使用decltype与std::extent结合使用。例如:

#include <iostream>
#include <type_traits> // std::remove_extent std::remove_all_extents std::rank std::extent

template<class T, size_t N>
constexpr size_t length(T(&)[N]) { return N; }

template<class T, size_t N>
constexpr size_t length2(T(&arr)[N]) { return sizeof(arr) / sizeof(*arr); }

int main()
{
    int a[5][4][3]{{{1,2,3}, {4,5,6}}, { }, {{7,8,9}}};

    // New way
    constexpr auto l1 = std::extent<decltype(a)>::value;     // 5
    constexpr auto l2 = std::extent<decltype(a), 1>::value;  // 4
    constexpr auto l3 = std::extent<decltype(a), 2>::value;  // 3
    constexpr auto l4 = std::extent<decltype(a), 3>::value;  // 0

    // Mixed way
    constexpr auto la = length(a);
    //constexpr auto lpa = length(*a);  // compile error
    //auto lpa = length(*a);  // get at runtime
    std::remove_extent<decltype(a)>::type pa;  // get at compile time
    //std::remove_reference<decltype(*a)>::type pa;  // same as above
    constexpr auto lpa = length(pa);
    std::cout << la << ' ' << lpa << '\n';

    // Old way
    constexpr auto la2 = sizeof(a) / sizeof(*a);
    constexpr auto lpa2 = sizeof(*a) / sizeof(**a);
    std::cout << la2 << ' ' << lpa2 << '\n';

    return 0;
}

BTY,获取多维数组中元素的总数:

constexpr auto l = sizeof(a) / sizeof(std::remove_all_extents<decltype(a)>::type);

或者把它放在一个函数模板中:

#include <iostream>
#include <type_traits>
    

template<class T>
constexpr size_t len(T &a)
{
    return sizeof(a) / sizeof(typename std::remove_all_extents<T>::type);
}

int main()
{
    int a[5][4][3]{{{1,2,3}, {4,5,6}}, { }, {{7,8,9}}};
    constexpr auto ttt = len(a);
    int i;
    std::cout << ttt << ' ' << len(i) << '\n';
    
    return 0;
}

更多如何使用它们的例子可以通过以下链接找到。


对于c++ /CX(在Visual Studio中使用c++编写UWP应用程序时),我们可以通过简单地使用size()函数来查找数组中值的数量。

源代码:

string myArray[] = { "Example1", "Example2", "Example3", "Example4" };
int size_of_array=size(myArray);

如果你计算size_of_array的输出将是:

>>> 4

Sizeof (array_name)给出整个数组的大小,Sizeof (int)给出每个数组元素的数据类型的大小。

所以用整个数组的大小除以数组中单个元素的大小就得到了数组的长度。

 int array_name[] = {1, 2, 3, 4, 5, 6};
 int length = sizeof(array_name)/sizeof(int);

我个人建议(如果你因为任何原因无法使用专门的函数)首先扩展数组类型的兼容性,超出你通常使用它的范围(如果你存储的值≥0:

unsigned int x[] -> int x[]

你会让数组的元素比你需要的要大。对于最后一个元素,你可以放置一些类型,包括在扩展类型说明符中,但你通常不会使用,例如,使用前面的例子,最后一个元素将是-1。这使您能够(通过使用for循环)找到数组的最后一个元素。


虽然这是一个老问题,但值得将答案更新到c++ 17。在标准库中,现在有一个模板化函数std::size(),它返回std容器或c风格数组中的元素数量。例如:

#include <iterator>

uint32_t data[] = {10, 20, 30, 40};
auto dataSize = std::size(data);
// dataSize == 4

我在这里提供了一个棘手的解决方案:

你总是可以在第一个元素中存储长度:

// malloc/new

arr[0] = length;
arr++;

// do anything. 
int len = *(arr-1);

free(--arr); 

代价是在调用free时必须—arr


你可以通过以下方法找到数组的长度:

int  arr[] = {1, 2, 3, 4, 5, 6}; 
int size = *(&arr + 1) - arr; 
cout << "Number of elements in arr[] is "<< size; 
return 0;

你可以简单地使用这段代码:

#include <iostream>
#include <string>
#include <array>

using namespace std;

int main()
{

  array<int,3> values;
  cout << "No. elements in valuea array: " << values.size() << " elements." << endl;
  cout << "sizeof(myints): " << sizeof(values) << endl;

}

这里是参考资料:http://www.cplusplus.com/reference/array/array/size/


你有很多选项可以用来获取C数组的大小。

int myArray[] = {0, 1, 2, 3, 4, 5, 7};

1) sizeof(<array>) / sizeof(<type>):

std::cout << "Size:" << sizeof(myArray) / sizeof(int) << std::endl;

2) sizeof(<array>) / sizeof(*<array>):

std::cout << "Size:" << sizeof(myArray) / sizeof(*myArray) << std::endl;

3) sizeof(<数组>)/ sizeof(<数组>[<元素>]):

std::cout << "Size:" << sizeof(myArray) / sizeof(myArray[0]) << std::endl;

答:

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

解释:

由于编译器为每种类型的数据设置了特定大小的内存块,而数组只是这些数据的一组,因此只需将数组的大小除以数据类型的大小。如果我有一个包含30个字符串的数组,我的系统会为数组的每个元素(字符串)留出24个字节。在30个元素时,总共是720个字节。720/24 == 30个元素。这个小而紧凑的算法是:

Int number_of_elements = sizeof(array)/sizeof(array[0]),这相当于

Number_of_elements = 720/24

请注意,您不需要知道数组是什么数据类型,即使它是自定义数据类型。


这是一个非常古老和传奇的问题,已经有很多惊人的答案。但是随着时间的推移,新的功能被添加到语言中,所以我们需要根据可用的新功能不断更新。

我只是注意到还没有人提到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()函数给出了字节数,所以在其他函数中,它将返回分配给指针的字节数,而不是整个数组。所以这种方法行不通。

但我相信你能根据你的要求找到一个好办法。

快乐的编码。


您可以使用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;
}

我认为这是可行的:

for(int i=0;array[i];i++)
{
 //do_something
}  

给你:

#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;
}