数组是专门用于在一系列内存区域中保留同类型数据的数据结构。使用数组的主要好处是我们可以使用索引参数从任何位置访问它们。然而,插入和删除数据需要顺序操作,这将使得这个数据结构变成线性数据结构。我们可以简单地使用方括号中的索引或位置号来从数组中提取元素。本文将演示如何在C++中从数组中读取最近的k个数字。
理解概念并通过示例进行说明
Given array A = [10, 14, 65, 85, 96, 12, 35, 74, 69]We have another number k = 4The number of elements in A is 9The output will be the last k elements from A, which are:12, 35, 74, 69
登录后复制
We have the elements inside the array for every array, and the quantity n is also crucial. The number n indicates how many valid elements are there in an array. The size of the array might not match the n. Although an array can have a maximum of Z elements, only n of them must be valid; the remaining slots are empty. In this case, k must be less than or equal to n in order to retrieve the kth element from the array. Before taking up the components, we must inspect it. For a better understanding, let’s have a look at the algorithm.
算法
读取一个数组 A 作为输入。同时接受元素的数量:n 和 k,以读取 A 中的前 k 个元素
创建一个空数组 B
立即学习“C++免费学习笔记(深入)”;
如果 k
for i in range 0 to k – 1, do
B[ i ] = A[ n – k + i ]
end for
end if
返回 B
Example
#include # define Z 50using namespace std;void displayArr(int arr[], int n){ for( int i = 0; iOutput
Given Array: 57, 10, 44, 19, 86, 52, 86, 14, 76, 65, 32, 14, The last 7 element from A: 52, 86, 14, 76, 65, 32, 14, The last 10 element from A: 44, 19, 86, 52, 86, 14, 76, 65, 32, 14,登录后复制
使用向量
在上述方法中,静态数组用于存储和检索数组元素。使用向量也可以实现相同的功能。向量是C++ STL的一部分,它是动态数组。让我们来看看代码。算法保持不变。
Example
#include #include # define Z 50using namespace std;void displayArr( vector v ){ for( int i = 0; i pickLastKElement( vector A, int k) { vector B; if( k A = {57, 10, 44, 19, 86, 52, 86, 14, 76, 65, 32, 14}; vector B; coutOutput
Given Array: 57, 10, 44, 19, 86, 52, 86, 14, 76, 65, 32, 14, The last 7 element from A: 52, 86, 14, 76, 65, 32, 14, The last 10 element from A: 44, 19, 86, 52, 86, 14, 76, 65, 32, 14,登录后复制
使用向量构造函数
最后一种方法是手动创建一个空向量,然后逐个复制元素。然而,我们可以直接使用向量迭代器在向量构造函数中复制最后k个元素。让我们看一下代码来理解这个概念。
Example
#include #include # define Z 50using namespace std;void displayArr( vector v ){ for( int i = 0; i pickLastKElement( vector A, int k) { vector B( A.begin() + (A.size() - k), A.end() ); return B;}int main() { vector A = {57, 10, 44, 19, 86, 52, 86, 14, 76, 65, 32, 14}; vector B; coutOutput
Given Array: 57, 10, 44, 19, 86, 52, 86, 14, 76, 65, 32, 14, The last 7 element from A: 52, 86, 14, 76, 65, 32, 14, The last 10 element from A: 44, 19, 86, 52, 86, 14, 76, 65, 32, 14,登录后复制
在这里,使用A向量的最后k个元素创建了B向量。使用begin() 方法获取第一个项的地址,并使用偏移量begin() (A.size() − k)作为结束点,这样就可以指向最后k个元素。
Conclusion
本文介绍了从给定数组中读取或选择最后n个数字的三种不同方法。第二种和第三种解决方案基于向量,而不是第一种方法使用的静态默认数组。前两个问题的答案很简单。我们使用for循环逐个复制最后k个元素。最后一种技术是最简单的,它使用向量构造函数通过使用另一个向量的迭代器来复制组件来生成一个向量。
以上就是获取数组中最后给定数量的项目的C++程序的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2586600.html