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

获取数组中最后给定数量的项目的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 登录后复制

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

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

  • end for

  • end if

  • 返回 B

  • Example

    #include 1. define Z 50 using namespace std; void displayArr(int arr[], int n){ for( int i = 0; i < n; i++ ){ cout