使用指针交换数组的内容

Swapping the content of an array using pointer

本文关键字:数组 交换 指针      更新时间:2023-10-16

在此处输入图像描述

这是问题的示例输出。我的交换部件运行不正常...

int *smallest, *current = array;
for(int i=0; i<MAX-1; i++, current++){ //partial code given by the question
smallest = current;
cout << "nCurrent=" << *current;
int tmp = *current;
for(int j = i; j < MAX; j++,smallest++){ //my code 
if(*smallest < tmp){
tmp = *smallest;
}
}
*smallest = tmp;
cout << " Smallest=" <<*smallest<< endl;
int tmp2; //not functioning from this line onwards
tmp2 = *smallest;
*smallest = *current;
*current = tmp2;
}

首先,您当然不需要 2 个 for 循环。话虽如此,您可能只是直接用于此任务的算法库:

https://en.cppreference.com/w/cpp/algorithm/min_element

#include <vector>
#include <algorithm>
int main(){
std::vector elements = {8,6,4,2,16};
return *std::min_element(std::begin(elements), std::end(elements));
}

自己尝试一下:https://godbolt.org/z/oHkMid

使用原始指针,您只需要这样做 - 如下所示:

return *std::min_element(array, array + MAX);

或者如果阵列具有已知大小

return *std::min_element(std::begin(array), std::end(array));

当你到达外部循环的最后一次迭代时,你只检查最后一个元素的最小值(主要问题是:你有两个循环(。

你不需要两个 for 循环来查找数组中的最小元素。它只能在数组的一次遍历中完成。

int *smallest, *current;
smallest = current = array;                     // both smallest and current refer to &array[0]
for (; current - array <= MAX - 1; ++current)   // current will increment till the last element of the array which is at MAX-1 distance from &array[0]
if (*current < *smallest)                   // if element at *current is less than element at *smallest then update smallest.
smallest = current;
current = nullptr;                              // current refers to the element at MAX distance from &array[0] hence it should be set to nullptr.
cout << *smallest << endl;

我不完全理解你的算法。如果你只想找到数组中最小的元素,你不需要两个for循环。

但是,我确实在您的代码中看到了一些问题。

for(int j = i ;j < MAX-i ; smallest++){ // Here you don't want to increment smallest !
// You only want to change smallest
// when *current is less than *smallest
// You probably want ++j instead
//
// Further "MAX-i" should be "MAX-1"
if(array[j] < *current){             // Here you don't want to compare array and *current
// Instead you want:
//     array[j] < *smallest
smallest = &array[i];            // Here you want to use j instead of i:
//      smallest = &array[j]
}
}

如果你"只是"想使用指针找到数组中最小的元素,你可以这样做:

int *smallest = array;
int *current = array;
for(int i=0; i<MAX-1; i++, current++){
cout << "nCurrent=" << *current;
if(*current < *smallest){
smallest = current;
}
cout << " Smallest=" <<*smallest<< endl;
}