gpt4 book ai didi

c++ - 通过提供指针数组作为参数对数组进行排序

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

我写了这段代码,但它只是给我一个地址:

#include<iostream>
using namespace std;

void swap(int* a,int* b)
{
int temp=*a;
*a=*b;
*b=temp;
}

void sort(int* p[],int n)
{
for(int i=0; i<n;i++)
{
if(*p[i]>*p[i+1])
swap(p[i],p[i+1]);
}
}

int main()
{
int arr[]={8,6,5,4,3,7,1};
int* p[7];

for(int i=0;i<7;i++)
{
p[i]=&arr[i];
}

sort(p,7);

/*i tried to change arr[1] to p[1] or *p[1] but same output*/
cout<<arr[1]<<arr[2];
return 0;
}

我觉得我在某个地方缺乏概念。完整的问题是这样的:

Write the following function that indirectly sorts the floats pointed to by the first n pointers in the array p by rearranging the pointers: void sort(float* p[],int n)

请帮忙。

最佳答案

这是一个更好的方法来做你想做的事情,有很多方法可以做得更好,但它看起来像你的 c++ 新手,所以我尽量让它尽可能简单。

#include "stdafx.h"
#include<iostream>
using namespace std;

//not needed, std::swap does the same job!
void swap(int *a, int *b)
{
std::swap(a, b);
}

//using a pointer to the array is better!
void sort(int arr[], int n)
{
//two loops are needed to sort the entire array!
for (int x(0); x < n - 1; x++)
{
//optimize the loop by removing already sorted items from loop
int sorted = n - x;
for (int y(0); y < sorted - 1; ++y)
if (arr[y] > arr[y + 1])
std::swap(arr[y], arr[y + 1]);
}
}


int main()
{
//vector or std::array better option!
int arr[] { 8,6,5,4,3,7,1 };

//provide the array to sort(), no need to make stuff harder
sort(arr, 7);

//Show you that the sort worked!
for (int ccc = 0; ccc < 7; ccc++)
std::cout << arr[ccc] << ' ';

std::cout << '\n';

cout << "Index 5: " << arr[5] << "\nIndex 6: " << arr[6] << "\n";

return 0;
}

这里有一个很好的数组排序教程:http://www.learncpp.com/cpp-tutorial/64-sorting-an-array-using-selection-sort/

关于c++ - 通过提供指针数组作为参数对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43165865/

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