使用指针交换数组的内容
Swapping the content of an array using pointer
在此处输入图像描述
这是问题的示例输出。我的交换部件运行不正常...
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;
}
相关文章:
- 通过交换元素使数组相同
- 如何在数组中交换最小和最大的位置?
- 交换函数不是在 C++ 中交换 2D 数组的元素
- 如何交换数组中的元素?
- C++:交换矩阵的行:使用单维数组
- 使用指针 c++ 交换结构数组中的元素
- 使用指针交换数组的内容
- C++数组交换并查找最小元素
- 使用指针交换而不引用数组C++
- 指针数组交换无需直接访问数组
- 交换数组
- 如何在C++中交换对象数组的 2 个不同对象
- 如何将元素的索引从2D数组存储到1D数组中,然后交换这些值
- 在C++中使用 2D 数组进行交换
- 代码是否交换数组的两个数字
- std::在 std::shared_ptr 之间交换,<A>其中 A 具有动态数组
- 在2D数组中交换行的最佳方法
- 如何在 2D 数组 c++ 中交换元素
- 交换二维数组中的两个值
- 如何使用数组交换对象,c++.我想改变