#include <bits/stdc++.h>
using namespace std;
/*Prototype for utility functions */
void printArray(int arr[], int size);
void swap(int arr[], int fi, int si, int d);
void leftRotate(int arr[], int d, int n)
{
/* Return If number of elements to be rotated
is zero or equal to array size */
if(d == 0 || d == n)
return;
/*If number of elements to be rotated
is exactly half of array size */
if(n - d == d)
{
swap(arr, 0, n - d, d);
return;
}
/* If A is shorter*/
if(d < n - d)
{
swap(arr, 0, n - d, d);
leftRotate(arr, d, n - d);
}
else /* If B is shorter*/
{
swap(arr, 0, d, n - d);
leftRotate(arr + n - d, 2 * d - n, d); /*This is tricky*/
}
}
/*UTILITY FUNCTIONS*/
/* function to print an array */
void printArray(int arr[], int size)
{
int i;
for(i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
/*This function swaps d elements starting at index fi
with d elements starting at index si */
void swap(int arr[], int fi, int si, int d)
{
int i, temp;
for(i = 0; i < d; i++)
{
temp = arr[fi + i];
arr[fi + i] = arr[si + i];
arr[si + i] = temp;
}
}
// Driver Code
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7};
leftRotate(arr, 2, 7);
printArray(arr, 7);
return 0;
}
// This code is contributed by Rath Bhupendra
我在geek for geeks网站上找到了此代码。该代码用于旋转数组的元素。在网站上被称为块交换算法,我的问题是:我们能否在传递参数(arr + n-d)的同时按左旋转函数else部分中的说明将整数添加到c++中的数组中?
我们如何将整数添加到数组?
我尝试将一个整数添加到在线编译器中的数组中,但它不起作用。但是上面的代码可以完美地提供所需的输出34567。
该网站的链接为https://www.geeksforgeeks.org/block-swap-algorithm-for-array-rotation/。
最佳答案
Can we add integers to an array in c++ as given in the else part of the left rotate function while passing the arguments (arr+n-d)?
How can we add integers to an array?
答案是你做不到,这不是这里发生的事情。
int arr[]
参数衰减到指向数组第一个元素的指针。这与使用int* arr
相同,因此您在arr + n - d
中所做的只是简单的指针算法。指针将相对于表达式计算前的位置移动
n - d
位置。假设
n - d
的结果为4,并且arr
指向作为参数传递的数组的开头,即&arr[0]
(以数组表示法)或arr + 0
(以指针表示法),这是它在初始状态下指向的位置,您将拥有arr + 4
或&arr[4]
,在求值之后,该表达式将提供对索引4(数组的第5个元素)的地址的访问。要访问该地址中的值,请使用*(arr + 4)
或arr[4]
。附带一提,我不建议您使用geeksforgeeks.com学习C++或任何其他语言,为此,应该阅读good book来完成。
关于c++ - 我们可以在C++中向数组添加整数吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63656228/