gpt4 book ai didi

c++ - 无法弄清楚为什么我的 Print Array 正在替换元素

转载 作者:行者123 更新时间:2023-11-30 04:43:50 26 4
gpt4 key购买 nike

我正在上 C++ 类(class),我们已经获得了指导。我们得到的任务基本上是通过传递指针作为各种函数的参数来对从文本文件中读取的数组进行冒泡排序。我认为我有一个不错的设置,可以输出我正在寻找的内容,但是对于特定的操作,当没有一个元素写入数组时,我得到一个零作为元素。

#include <iostream>
#include <fstream>

using namespace std;

int capacity;
int count;

int readData(int *&arr);
void swap(int *xp, int *yp);
void bsort(int *arr, int last);
void writeToConsole(int *arr, int last);
void bubble_sort(int *arr, int last, int(*ptr)(int, int));
int ascending(int a, int b);
int descending(int a, int b);

int main() {

int *whatever = NULL;
count = readData(whatever);
cout << "Raw array data:" << endl;
writeToConsole(whatever, capacity);
cout << "After simple bubble sort:" << endl;
bubble_sort(whatever, capacity, ascending);
writeToConsole(whatever, capacity);
cout << "Now descending:" << endl;
bubble_sort(whatever, capacity, descending);
writeToConsole(whatever, capacity);


return 0;
}

int readData(int *&arr) {
ifstream inputFile;
inputFile.open("data.txt");
if (!inputFile) {
cout << "Error!";
}
inputFile >> capacity;
arr = new int[capacity];
for(int i = 0; i < capacity; i++){
inputFile >> arr[i];
}
inputFile.close();
return capacity;
}

void swap(int *xp, int *yp) {
int temp = *xp;
*xp = *yp;
*yp = temp;
}

void bsort(int *arr, int last) {
int i, j;
bool swapped;
for (i = 0; i < last + 1; i++)
{
swapped = false;
for (j = 0; j < last-i; j++)
{
if (arr[j] > arr[j+1])
{
swap(arr[j], arr[j+1]);
swapped = true;
}
}
// IF no two elements were swapped by inner loop, then break
if (swapped == false)
break;
}
}

void writeToConsole(int *arr, int last) {

cout << "[ ";
for(int i = 0; i < last; i++){
cout << arr[i] << " ";
}
cout << "]" << endl;
}

void bubble_sort(int *arr, int last, int(*ptr)(int, int)){
int i, j;
bool swapped;
for (i = 0; i < last; i++)
{
swapped = false;
for (j = 0; j < last-i; j++)
{
//Use the function pointer to determine which logic to use
if (ptr(arr[j] , arr[j+1]))
{
swap(arr[j], arr[j+1]);
swapped = true;
}
}

// IF no two elements were swapped by inner loop, then break
if (swapped == false)
break;
}
}

int ascending(int a, int b){
return a > b;
}

int descending(int a, int b){
return a < b;
}

我的输出看起来像这样:

原始数组数据:[ 8 4 7 2 9 5 6 1 3 ]简单冒泡排序后:[ 0 1 2 3 4 5 6 7 8 ]现在下降:[ 9 8 7 6 5 4 3 2 1 ]

关于为什么我的第二个排序要输入零有什么想法吗?谢谢!

最佳答案

你必须在 bubble_sort 函数中做这个改变

for (j = 1; j < last - i; j++)
{
//Use the function pointer to determine which logic to use
if (ptr(arr[j-1], arr[j]))
{
swap(arr[j-1], arr[j]);
swapped = true;
}
}

关于c++ - 无法弄清楚为什么我的 Print Array 正在替换元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57996510/

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