获取数组中最后给定数量的项目的C++程序

2023年 8月 27日 22.9k 0

获取数组中最后给定数量的项目的C++程序

数组是专门用于在一系列内存区域中保留同类型数据的数据结构。使用数组的主要好处是我们可以使用索引参数从任何位置访问它们。然而,插入和删除数据需要顺序操作,这将使得这个数据结构变成线性数据结构。我们可以简单地使用方括号中的索引或位置号来从数组中提取元素。本文将演示如何在C++中从数组中读取最近的k个数字。

理解概念并通过示例进行说明

Given array A = [10, 14, 65, 85, 96, 12, 35, 74, 69]
We have another number k = 4
The number of elements in A is 9

The 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

  • 如果 k < n,则

    • for i in range 0 to k - 1, do

      • B[ i ] = A[ n - k + i ]

    • end for

  • end if

  • 返回 B

Example

#include
# define Z 50

using namespace std;

void displayArr(int arr[], int n){
for( int i = 0; i < n; i++ ){
cout

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论