【发布时间】:2018-09-28 14:29:58
【问题描述】:
我正在编写一个程序,该程序接受用户输入的最多 25 个整数的列表,然后使用冒泡排序打印排序列表,排序列表按降序排列,以及关于列表的其他一些信息,如中位数、最小值和最大值和模式。
我已经在我使用初始化列表(不是来自用户输入/cin)创建的数组上单独测试了程序中的所有函数,它们工作正常,但是当我运行程序时,出现了问题。例如,当我输入 1,2,3,4 时,按降序打印排序列表的函数会打印 3,2,1,-858993460。无论我将什么值放入输入数组,它总是会忽略最大的整数并在最后添加 -858993460。这是我的代码的相关部分:
#include <iostream>
using namespace std;
void input(int ulist[26], int& n);
void Bubblesort(int ulist[26], int slist[26], int n);
void print(int list[26], int n);
int n;
void reversesort(int slist[26], int n);
void main()
{
int ulist[26], slist[26];
input(ulist, n);
cout << "Unsorted";
print(ulist, n);
cout << "Sorted";
Bubblesort(ulist, slist, n);
print(slist, n);
reversesort(slist, n);
cin >> n;
}
void input(int ulist[26], int& n)
{
int i(0), value;
cout << "enter value : \n";
cin >> value;
while (i < 25 && value != -999)
{
ulist[i] = value;
i++;
if (i < 25)
{
cin >> value;
}
}
n = i;
}
void Bubblesort(int ulist[26], int slist[26], int n)
{
int i, j, temp;
for (i = 0; i < n; i++)
slist[i] = ulist[i];
for (j = 25 - 1; j > 0; j--) //25 is Length of the array
for (i = 0; i < j; i++)
if (slist[i] > slist[i + 1])
{
temp = slist[i];
slist[i] = slist[i + 1];
slist[i + 1] = temp;
}
}
void print(int list[26], int n)
{
int i;
cout << " list of numbers are : \n";
for (i = 0; i < n; ++i)
{
cout << list[i] << '\n';
}
cout << "\n\n";
}
void reversesort(int slist[26], int n) //checked w online compiler, works
{
cout << "List of numbers in descending order is: \n";
for (int i = n - 1; i >= 0; --i)
cout << slist[i] << ", ";
cout << "\n";
}
我假设这是某种内存问题,并且它的根源与通过我编写的函数传递在气泡排序函数中修改的 slist 有关。我对 C++(来自 python)很陌生,所以我假设我在将数组传递给函数方面遗漏了一些东西。
编辑:我想总结一下 - 如何获取输入函数中输入的数据并在另一个函数中使用该数组?以及如何获取已经通过bubblesort函数排序的数组并在另一个函数中使用该数组?
【问题讨论】:
-
reversesort打印slist[0],但没有其他函数会分配给索引为零的元素。 -
C++ 中的数组索引从 0 开始,而不是从 1。可能这就是您访问无效值的原因。
-
你应该使用标准的 STL 容器(例如
std::array),这对你来说肯定比使用类 C 的表更小,这在 C++ 中是一种不好的做法。跨度> -
哦,旁注:
foo(int[26])等价于foo(int[])和foo(int*)。无论如何,您的数组都会衰减为指针,因此编译器会忽略它。 -
"我假设这是某种内存问题" - 所以你在 Valgrind 下运行它来检查,然后呢?值得包括您迄今为止的调查结果。