gpt4 book ai didi

c++:选择使用指针而不是索引进行排序

转载 作者:行者123 更新时间:2023-11-28 06:05:17 28 4
gpt4 key购买 nike

我想使用指针而不是索引对数字进行排序。顺便说一句,这是头文件:

int * sort(const int * const array, int size)

下面是我得到的源代码

void selectionSort(int list[], int arraySize)
{
for(int i=arraySize-1; i>=1; i--)
{
int currentMax=list[0];
int currentMaxIndex=0;

for(int j=1; j<=i; j++)
{
if(currentMax=list[j])
{
currentMax=list[i];
currentMaxIndex=j;
}
}
if(currentMaxIndex != i)
{
list[currentMaxIndex]=list[i];
list[i]=currentMax;
}
}
}

我知道您可以将 list[i] 切换为 *(list+i) 但我不知道如何使用“currentMaxIndex”来实现。非常感谢您的帮助!!

最佳答案

C 中的指针与任何其他指针一样都是整数,可以与通常的操作进行比较。

所以你可以这样做:

int *end = list + length; // Create a pointer to one-past the end of an array
for(int *it = list; it < end; it++){ /* use it to read the elements */ }
int *my_favorite_index = list + some_index;

我不会为你解决作业,但我希望这对你有所帮助。

关于c++:选择使用指针而不是索引进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32505595/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com