简介
在本文中,我们将了解在C++中找到数组长度 的各种方法。
基本上,当我们说数组的长度时,实际上我们指的是相应数组中存在的元素的总数。例如,对于下面给出的数组:
1int array1[] = { 0, 1, 2, 3, 4 }
这里数组的大小或长度等于数组中元素的总数。在本例中是‘5 ’。
在C++中查找数组长度的方法
现在让我们看看在C++中计算数组长度的不同方法,它们如下所示:
1.逐个元素统计,
2.egin()
和end()
,
3.sizeof()
函数,
4.STL中的Size()
函数,
5.注意事项。
现在,让我们通过实例详细讨论每种方法。
1.逐个元素统计
遍历给定的数组,同时计算我们遍历的元素总数,可以得到数组的长度,对吗?
但是对于遍历,如果我们事先不知道数组的长度,就不能直接使用for循环。这个问题可以通过使用一个简单的for-each循环来解决。仔细看看下面的代码。
1#include<iostream>
2#include<array>
3using namespace std;
4int main()
5{
6 int c;
7 int arr[]={1,2,3,4,5,6,7,8,9,0};
8 cout<<"The array is: ";
9 for(auto i: arr)
10 {
11 cout<<i<<" ";
12 c++;
13 }
14 cout<<"\nThe length of the given Array is: "<<c;
15
16 return 0;
17}
输出:
1The array is: 1 2 3 4 5 6 7 8 9 0
2The length of the given Array is: 10
在这里,正如我们所说的,我们使用带迭代器的For-Each loopi 遍历整个数组ARR。同时,计数器** c** 递增。最后,当遍历结束时,** c** 保存给定数组的长度。
2.使用Begin()和End()
我们还可以使用标准库的egin()
和end()
函数计算数组的长度。这两个函数分别返回指向相应数组的开始 和** 结束** 的迭代器。仔细查看给定的代码,
1#include<iostream>
2#include<array>
3using namespace std;
4int main()
5{
6 //Given Array
7 int arr[] = { 11, 22, 33, 44 };
8
9 cout<<"The Length of the Array is : "<<end(arr)-begin(arr); //length
10
11 return 0;
12}
输出:
1The Length of the Array is : 4
因此,在这里我们可以看到,两个函数end()
和egin()
的返回值之间的差异给出了给定数组arr
的大小或长度。也就是说,在我们的例子中,4 。
3.C++中使用sizeof()函数查找数组长度
C++ 中的sizeof()
运算符返回传递的变量或数据的大小,单位为字节。同样,它也返回存储数组所需的总字节数。因此,如果我们简单地将数组的大小除以数组的每个元素获取的大小,我们就可以得到数组中存在的元素的总数。
让我们看看它是如何工作的
1#include<iostream>
2#include<array>
3using namespace std;
4int main()
5{ //Given array
6 int arr[] = {10 ,20 ,30};
7
8 int al = sizeof(arr)/sizeof(arr[0]); //length calculation
9 cout << "The length of the array is: " <<al;
10
11 return 0;
12}
输出:
1The length of the array is: 3
正如我们所看到的,我们得到了我们想要的输出。
4.在STL中使用Size()函数
我们在标准库中定义了size()
函数,该函数返回给定容器(在本例中为数组)中的元素数量。
1#include<iostream>
2#include<array>
3using namespace std;
4int main()
5{ //Given array
6 array<int,5> arr{ 1, 2, 3, 4, 5 };
7 //Using the size() function from STL
8 cout<<"\nThe length of the given Array is: "<<arr.size();
9 return 0;
10}
输出:
1The length of the given Array is: 5
如您所愿,我们将获得如上所示的输出。
5.在C++中使用指针查找数组长度
我们还可以使用指针 找到给定数组的长度。让我们看看如何
1#include<iostream>
2#include<array>
3using namespace std;
4int main()
5{ //Given array
6 int arr[6] = {5,4,3,2,1,0};
7
8 int len = *(&arr + 1) - arr;
9 //*(&arr + 1) is the address of the next memory location
10 // just after the last element of the array
11
12 cout << "The length of the array is: " << len;
13
14 return 0;
15}
输出:
1The length of the array is: 6
表达式* (n +1)
给出了数组最后一个元素之后的内存空间的地址。因此,它与数组的起始位置或基址(* )之间的差值为我们提供了给定数组中存在的元素的总数。
结论
因此,在本教程中,我们讨论了在 C++ 中查找数组长度的各种方法。尽管上面的每个例子都很容易使用,但我们更喜欢使用** for-each** 循环的例子。这不仅是因为代码的可读性,还因为它的跨平台可靠性。
对于任何进一步的问题,请随时使用下面的评论。
参考文献
- 如何找到array?堆栈溢出问题的长度,
- For-Each循环in C++-JournalDev POST。