c++获取数组长度查找算法

介绍 (Introduction)

In this article, we are going to learn about the various ways following which we can find array length in C++.

在本文中,我们将学习在C ++中可以找到数组长度的各种方法。

Basically, when we say the length of an array actually we refer to the total number of elements present in the corresponding array. For example, for an array as given below:

基本上,当我们说一个数组的长度时,实际上是指相应数组中存在的元素总数。 例如,对于下面给出的数组:


int array1[] = { 0, 1, 2, 3, 4 }

The size of the array or length of the array here is equal to the total number of elements in it. Which, in this case, is ‘5‘.

此处数组的大小或数组的长度等于数组中元素的总数。 在这种情况下为“ 5 ”。

在C ++中查找数组长度的方法 (Ways to find Length of an Array in C++)

Now let us take a look at the different ways following which we can find the length of an array in C++, they are as follow:

现在让我们看一下在C ++中可以找到数组长度的不同方法,它们如下:

  1. Counting element-by-element,逐元素计数
  2. begin() and end(),begin()end()
  3. sizeof() function,sizeof()函数,
  4. size() function in STL,STL中的size()函数,
  5. Pointers.指针。

Now, let us discuss each method one-by-one with examples and in detail.

现在,让我们与示例逐一讨论详细的方法。

1.逐元素计数 (1. Counting element-by-element)

Traversing throughout the given array and simultaneously counting the total number of elements we traversed can give us the length of the array right?

在给定数组中遍历并同时计算遍历的元素总数可以使我们知道数组的长度对吗?

But for traversing we cannot use a for loop directly if we do not know the array length beforehand. This issue can be solved by using a simple for-each loop. Look at the code below carefully.

但是对于遍历,如果我们事先不知道数组长度,则不能直接使用for循环。 通过使用简单的for-each循环可以解决此问题。 仔细看下面的代码。


#include<iostream>
#include<array>
using namespace std;
int main()
{int c;int arr[]={1,2,3,4,5,6,7,8,9,0};cout<<"The array is: ";for(auto i: arr){cout<<i<<" ";c++;}cout<<"\nThe length of the given Array is: "<<c;return 0;
}

Output:

输出:


The array is: 1 2 3 4 5 6 7 8 9 0
The length of the given Array is: 10

Here, as we said, we traverse through the entire array arr using a for-each loop with iterator i. Simultaneously the counter, c is incremented. At last, when the traversing is over, c holds the length of the given array.

正如我们所说,这里我们使用带有迭代器i的for-each循环遍历整个数组arr。 同时,计数器c递增。 最后,当遍历结束时, c保留给定数组的长度。

2.使用begin()和end() (2. Using begin() and end())

We can also calculate the length of an array using the standard library’s begin() and end() functions. The two functions return iterators pointing to the start and the end of the corresponding array respectively. Take a close look at the given code,

我们还可以使用标准库的begin()end()函数来计算数组的长度。 这两个函数返回分别指向相应数组开始结束的迭代器。 仔细看看给定的代码,


#include<iostream>
#include<array>
using namespace std;
int main()
{  //Given Arrayint arr[] = { 11, 22, 33, 44 };cout<<"The Length of the Array is : "<<end(arr)-begin(arr); //lengthreturn 0;
}

Output:

输出:


The Length of the Array is : 4

Hence, here as we can see, the difference between the return values of the two functions end() and begin() give us the size or length of the given array, arr. That is, in our case, 4.

因此,在这里我们可以看到,两个函数end()begin()的返回值之间的差为我们提供了给定数组arr的大小或长度。 也就是说,在我们的例子中是4

3.在C ++中使用sizeof()函数查找数组长度 (3. Using sizeof() function to Find Array Length in C++)

The sizeof() operator in C++ returns the size of the passed variable or data in bytes. Similarly, it returns the total number of bytes required to store an array too. Hence, if we simply divide the size of the array by the size acquired by each element of the same, we can get the total number of elements present in the array.

C ++中sizeof()运算符返回传递的变量或数据的大小(以字节为单位)。 同样,它也返回存储数组所需的字节总数。 因此,如果我们简单地将数组的大小除以相同元素每个元素获取的大小,就可以获得数组中存在的元素总数。

Let us how that works

让我们看看它是如何工作的


#include<iostream>
#include<array>
using namespace std;
int main()
{  //Given arrayint  arr[] = {10 ,20 ,30};int al = sizeof(arr)/sizeof(arr[0]); //length calculationcout << "The length of the array is: " <<al;return 0;
}

Output:

输出:


The length of the array is: 3

As we can see, we get our desired output.

如我们所见,我们获得了所需的输出。

4.在STL中使用size()函数 (4. Using the size() function in STL)

We have the size() function defined in the standard library which returns the number of elements in the given container(array in our case).

我们在标准库中定义了size()函数,该函数返回给定容器(在本例中为数组)中元素的数量。


#include<iostream>
#include<array>
using namespace std;
int main()
{  //Given arrayarray<int,5> arr{ 1, 2, 3, 4, 5 };//Using the size() function from STLcout<<"\nThe length of the given Array is: "<<arr.size();return 0;
}

Output:

输出:


The length of the given Array is: 5

As desired, we get the output as shown above.

根据需要,我们得到如上所示的输出。

5.使用指针在C ++中查找数组长度 (5. Using Pointers to Find Array Length in C++)

We can also find the length of a given array using pointers. Let us see how

我们还可以使用指针找到给定数组的长度。 让我们看看


#include<iostream>
#include<array>
using namespace std;
int main()
{  //Given arrayint  arr[6] = {5,4,3,2,1,0};int len = *(&arr + 1) - arr;//*(&arr + 1) is the address of the next memory location// just after the last element of the arraycout << "The length of the array is: " << len;return 0;
}

Output:

输出:


The length of the array is: 6

The expression *(arr+1) gives us the address of the memory space just after the array’s last element. Hence, the difference between it and the arrays starting location or the base address(arr) gives us the total number of elements present in the given array.

表达式*(arr+1)为我们提供了数组最后一个元素之后的内存空间地址。 因此,它与数组起始位置或基地址( arr )之间的差异为我们提供了给定数组中存在的元素总数。

结论 (Conclusion)

So, in this tutorial, we discussed the various methods to find array length in C++. Even though each one of the above examples is easy to go with, we prefer the one using the for-each loop. Not only because of code readability but also for its cross-platform reliability.

因此,在本教程中,我们讨论了在C ++中查找数组长度的各种方法。 即使上面的每个示例都很容易使用,我们还是更喜欢使用for-each循环的示例。 不仅由于代码可读性,而且还因为其跨平台的可靠性。

For any further questions feel free to use the comments below.

如有任何其他疑问,请随时使用以下评论。

参考资料 (References)

  • How do I find the length of an array? – Stack Overflow question,如何找到数组的长度? –堆栈溢出问题,
  • for-each loop in C++ – JournalDev post.C ++中的for-each循环 – JournalDev发布。

翻译自: https://www.journaldev.com/37594/find-array-length-in-c-plus-plus

c++获取数组长度查找算法

c++获取数组长度查找算法_在C ++中查找数组长度相关推荐

  1. selenium查找文本_在Selenium中查找具有链接文本和部分链接文本的元素

    selenium查找文本 Selenium中CSS定位器是一个基本概念,每个旨在使用Selenium执行自动化测试的测试人员都应该意识到这一点. 在Selenium中充分使用CSS定位器可以帮助您以更 ...

  2. python从键盘输入一个列表计算输出元素的平均值_python列表查找值_在Python中查找列表平均值的5种方法...

    python列表查找值 Hi Folks! In this article, we will have a look at the various ways to find the average o ...

  3. java 查找素数_在Java中查找和检查素数

    java 查找素数 什么是质数? (What is a Prime Number?) A prime number is a natural number greater than 1 that is ...

  4. python二分法查找算法_顺序查找算法和折半(二分法)查找算法,C语言查找算法详解...

    查找是指在大量的信息中寻找一个特定的信息.在计算机中,查找是非常重要的一个应用,比如"百度".查找算法的好坏直接影响查找的速度. 常用的查找算法主要有顺序查找和折半(二分法)查找: ...

  5. python 查找算法_七大查找算法(Python)

    查找算法 -- 简介 查找(Searching)就是根据给定的某个值,在查找表中确定一个其关键字等于给定值的数据元素. 查找表(Search Table):由同一类型的数据元素构成的集合 关键字(Ke ...

  6. cb32a_c++_STL_算法_查找算法_(5)adjacent_find

    cb32a_c++_STL_算法_查找算法_(5)adjacent_find adjacent_find(b,e),b,begin(),e,end() adjacent_find(b,e,p),p-p ...

  7. 考研数据结构之查找(9.8)——练习题之编写一个函数利用二分查找算法在一个有序表中插入关键字k并保持表的有序性(C表示)

    题目 编写一个函数,利用二分查找算法在一个有序表中插入一个关键字k,并保持表的有序性. 分析 先在有序表中利用二分查找算法查找关键字值等于或小于k的结点,m指向正好等于k的结点或l指向关键字正好大于k ...

  8. 查找算法4——基于树的查找

    基于树的查找 基于树的查找法就是把待查找的表组织成树形结构再进行查找的方法.基于树的查找最常用的是基于二叉树的查找. 二叉排序树的创建和插入操作 编写算法,要求根据一个元素序列创建一棵二叉排序树,并将 ...

  9. Python查找算法(三)------ 插值查找

    算法简介 插值查找时根据要查找的关键字key与查找表中最大最小记录的关健字比较后的查找方法. 其核心就在于插值的计算公式: (key-a[low])/(a[high]-a[low])*(high-lo ...

最新文章

  1. js blob 下载到本地文件
  2. 4.1邮箱的全选,全不选,反选
  3. 转型从思维习惯的转变开始
  4. 外设驱动库开发笔记18:MS5837压力变送器驱动
  5. redis专题:redis的持久化方式有哪些?redis数据的备份和恢复策略
  6. oracle添加分区语句_Oracle表创建分区如何实现?
  7. cocos2d-x 10.1版本 修复真机上白屏问题
  8. 你为什么选择计算机应用专业,致新生!我为什么选择信息工程系
  9. 获取网页html内容
  10. plc梯形图如何转c语言,梯形图和指令怎么转换?plc梯形图转换指令表
  11. 终极版Python打包exe文件,并修改图标,这将是你见过最详细的教程~
  12. 关乎Java多线程+Runnable和Thread…
  13. Centos7命令行连接wifi网络,手机usb共享网络
  14. RFID固定资产定位管理系统-智慧资产人员可视化管理系统
  15. puzzle(0112)不规则数独、变种数独
  16. 利用百度APIStoreSDK获取Json数据并解析加载到ListView上
  17. 传统责任链模式和变种责任链模式
  18. java mysql SSM实现的校园门户平台网站系统源码+含开题报告与需求分析+包安装配置
  19. Python书籍教学游戏《外星人入侵》:‘pygame.Rect‘ object has no attribute ‘blit‘
  20. TPAMI 2022 | 寻找属于你的影子,港中文等提出实例阴影检测任务

热门文章

  1. android学习-仿Wifi模块实现
  2. System.Web.AspNetHostingPermission 类型的权限已失败
  3. iOS 创建推送证书
  4. web工程本地跟tomcat部署导致根路径不一致问题
  5. 【已解决】python远程连接数据库问题
  6. [转载] python中的type和object详解
  7. django models 配置
  8. Python3模块: hashlib
  9. 杭电2391--Filthy Rich(DP)
  10. asp.net 将ppt,word转化为pdf实现在线浏览详解