通过提供指针数组作为参数对数组进行排序
Sorting an array by providing an array of pointers as arguments
我写了这段代码,但它只给了我一个地址:
#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;
}
我想我在某处缺乏概念。完整的问题是:
编写以下函数,通过重新排列指针间接排序数组 p 中前 n 个指针指向的浮点数: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/
首先,您的代码具有缓冲区溢出,这意味着未定义的行为,因此根据定义,它所做的任何事情都是正确的。在sort
索引i
遍历从 0 到 n-1 的所有数组位置。但是你访问i+1
,这是数组之外的一个元素。对我来说,代码段错误。
更正后,输出为"54",这是发生的事情。
swap 函数交换arr
中的值,而不是交换p
中的指针。该练习要求您间接对数组进行排序,从而威胁指针。你需要在那里使用**或*&。因此,在排序循环中发生的情况是交换 8 和 6,然后交换 8 和 5,交换 8 和 4,依此类推。所以你的数组是 {6,5,4,3,7,1,8}。最后输出 arr[1] 和 [2],即 5 和 4。由于您没有在它们之间输出空格,因此您会得到"54"。
相关文章:
- C++函数模板需要 &for 数组参数
- C++ 数组参数不起作用
- 使用数组参数进行函数专用化
- 为什么我的数组参数的方法无法正常工作?(C )
- SWIG - Java 代理类数组参数
- 在 gcc 中使用数组参数编译外部"c"代码
- 从 VB6 调用的 C++ DLL 函数中的输出数组参数
- 如何根据数组参数项类型重载 IDL 中的函数
- 引用谷歌测试/模拟框架中的数组参数
- C++将数组参数传递给函数
- 字符星形数组参数未正确终止
- 如何将德尔菲的"字符串数组"参数翻译成C++?
- 为什么 gcc 无法推断数组参数的模板化大小?(C++11)
- 使用 const char 数组参数分析 constexpr 显示运行时执行
- C++指针数组参数
- 固定大小的多维数组参数
- 为什么数组参数被视为常量数组
- 如何在pgsql中格式化数组参数
- C++字符数组参数在x86编译中包含奇怪的字符
- 对象数组参数 - 错误:字段“字母”的类型不完整