简体   繁体   English

C ++:基本数组交换

[英]C++: A Basic Array Swap

I simply could not understand why the following code does not work. 我根本不明白为什么以下代码不起作用。 What could be the possible reason that the swap operation does not work; 交换操作不起作用的可能原因是什么?

#include <iostream>

using namespace std;

void rotateK(int* arr, int start, int finish) {
    int temp;
    for(int i=0;i<=finish;i++) {
        temp=arr[i];
        arr[i]=arr[finish-i];
        arr[finish-i]=temp;
    }
    for(int i=0;i<=finish;i++)
        cout<<arr[i]<<" ";
    cout<<endl;
}


int main(){
    int arr[5]={1,2,3,4,5};
    rotateK(arr,0,4);
    return 0;

}

It does work (although not how you want it to work). 它确实可以工作(尽管不是您希望它如何工作)。 But swaps the elements twice , that's why the processed array is identical to the original one. 但是将元素交换两次 ,这就是为什么处理后的数组与原始数组相同。

You probably want: 您可能想要:

for(int i=0 ; i<=finish/2 ; i++)

or even 甚至

for(int i=start;i<=(finish-start)/2 + start;i++)

so that you actually use start . 以便您实际使用start

You're swapping elements twice. 您要交换元素两次。 You can consider this idea of flipping a segment of an array. 您可以考虑翻转数组段的想法。

int i = start;
int j = finish;
while( i < j ) {
    temp=arr[i];
    arr[i]=arr[j];
    arr[j]=temp;
    ++i; --j;
}

It's difficult to make a mistake if you write it like this. 如果这样写,很难犯一个错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM