下面的代码是关于按某个值 d 旋转排序的数组
the following code is about rotating a sorted arrray by some value d
我的代码不工作,它产生了意外的结果results.the代码是关于使用临时数组进行数组旋转的。函数 "rotate" 旋转数组,而函数 printArray 打印数组。在主函数中,这两个函数都被调用。然后是 "hello" 的 cout。如果 "ellolloloohello" 的整体输出。为什么我得到这个 output.thanks
#include<iostream>
using namespace std;
void rotate(int arr[],int d, int n){
int temp[d];
for(int i =0;i<d;i++){
temp[i]=arr[i];
}
for(int i = 0;i<n-d;i++){
arr[i] = arr[i+d];
}
for(int i =0 ;i < d;i++)
{
temp[i]= arr[n-d+i];
}
}
void printArray(int arr[],int size){
for(int i =0;i<size;i++)
{
cout<<arr[i]+" " ;
}
}
int main()
{
int arr[10] = {0,1,2,3,4,5,6,7,8,9};
rotate(arr,3,10);
printArray(arr,10);
cout <<"hello";
}
;
输出是 "ellolloloohello" 而不是 "hello"。这里发生了什么?????
将cout<<arr[i]+" " ;
更改为cout << arr[i] << ' ';
请使用std::vector。 int arr[d]
不是 c++ :(
对于初学者来说,可变长度数组
void rotate(int arr[],int d, int n){
int temp[d];
//...
不是标准的 C++ 功能。要么使用辅助标准容器,例如 std::vector 或 std::list,要么你应该动态分配一个数组。
在函数的最后一个循环中
void rotate(int arr[],int d, int n){
int temp[d];
for(int i =0;i<d;i++){
temp[i]=arr[i];
}
for(int i = 0;i<n-d;i++){
arr[i] = arr[i+d];
}
for(int i =0 ;i < d;i++)
{
temp[i]= arr[n-d+i];
}
}
您正在覆盖数组 temp 而不是数组 arr。
而在这个语句中的函数printArray
cout<<arr[i]+" " ;
在表达式中
arr[i]+" "
这里用到了指针运算。也就是说,字符串文字 " "
被隐式转换为指向其第一个元素的指针,数值 arr[i]
用作该指针的偏移量。而是写
cout<<arr[i] << " " ;
我的代码不工作,它产生了意外的结果results.the代码是关于使用临时数组进行数组旋转的。函数 "rotate" 旋转数组,而函数 printArray 打印数组。在主函数中,这两个函数都被调用。然后是 "hello" 的 cout。如果 "ellolloloohello" 的整体输出。为什么我得到这个 output.thanks
#include<iostream>
using namespace std;
void rotate(int arr[],int d, int n){
int temp[d];
for(int i =0;i<d;i++){
temp[i]=arr[i];
}
for(int i = 0;i<n-d;i++){
arr[i] = arr[i+d];
}
for(int i =0 ;i < d;i++)
{
temp[i]= arr[n-d+i];
}
}
void printArray(int arr[],int size){
for(int i =0;i<size;i++)
{
cout<<arr[i]+" " ;
}
}
int main()
{
int arr[10] = {0,1,2,3,4,5,6,7,8,9};
rotate(arr,3,10);
printArray(arr,10);
cout <<"hello";
}
;
输出是 "ellolloloohello" 而不是 "hello"。这里发生了什么?????
将cout<<arr[i]+" " ;
更改为cout << arr[i] << ' ';
请使用std::vector。 int arr[d]
不是 c++ :(
对于初学者来说,可变长度数组
void rotate(int arr[],int d, int n){
int temp[d];
//...
不是标准的 C++ 功能。要么使用辅助标准容器,例如 std::vector 或 std::list,要么你应该动态分配一个数组。
在函数的最后一个循环中
void rotate(int arr[],int d, int n){
int temp[d];
for(int i =0;i<d;i++){
temp[i]=arr[i];
}
for(int i = 0;i<n-d;i++){
arr[i] = arr[i+d];
}
for(int i =0 ;i < d;i++)
{
temp[i]= arr[n-d+i];
}
}
您正在覆盖数组 temp 而不是数组 arr。
而在这个语句中的函数printArray
cout<<arr[i]+" " ;
在表达式中
arr[i]+" "
这里用到了指针运算。也就是说,字符串文字 " "
被隐式转换为指向其第一个元素的指针,数值 arr[i]
用作该指针的偏移量。而是写
cout<<arr[i] << " " ;