【发布时间】:2014-03-05 17:52:50
【问题描述】:
基本上,我正在尝试根据输入设置数组的大小(将要求用户提供 numArraySize)。我在 main 中创建了一个数组指针,并希望将此指针传递给函数。
#include <iostream>
using namespace std;
// Algorithm for Insertion Sort
int numArraySize;
void inputNums(int numArray[])
{
cout << "Enter a bunch of numbers: " ;
for(int x=0; x<numArraySize; x++)
{
cin >> numArray[x];
}
}
void outputNums(int numArray[])
{
for(int x=0; x<numArraySize; x++)
{
cout << numArray[x];
if(x != numArraySize-1)
{
cout << " - ";
}
}
}
void insertionSort(int numArray[])
{
int num;
int i;
for(int j=1; j<numArraySize; j++)
{
num = numArray[j];
i = j-1;
while(i>=0 && numArray[i] > num)
{
numArray[i+1] = numArray[i];
i--;
}
numArray[i+1] = num;
}
}
int main()
{
int *numbers = new int[numArraySize];
int choice;
cout << "1) Insertion Sort" << endl;
cout << "Enter your choice: " << endl;
cin >> choice; // Input choice for which algorithm to use
if(choice == 1)
{
cout << "Enter size of the array: ";
cin >> numArraySize;
inputNums(numbers); // Insert numbers
insertionSort(numbers); // Use algorithm to sort then output
outputNums(numbers);
}
cout << endl;
return 0;
}
编辑:
好的,我修复了错误。我变了: “int numArraySize=1;” 和位置 "int *numbers = new int[numArraySize];"
问题是无论如何我都必须初始化 numArraySize。这显然会导致错误。第二个问题是我必须在初始化之前输入 numArraySize 主函数中的“int *numbers”。
#include <iostream>
using namespace std;
// Algorithm for Insertion Sort
int numArraySize=1;
void inputNums(int numArray[])
{
cout << "Enter a bunch of numbers: " ;
for(int x=0; x<numArraySize; x++)
{
cin >> numArray[x];
}
}
void outputNums(int numArray[])
{
for(int x=0; x<numArraySize; x++)
{
cout << numArray[x];
if(x != numArraySize-1)
{
cout << " - ";
}
}
}
void insertionSort(int numArray[])
{
int num;
int i;
for(int j=1; j<numArraySize; j++)
{
num = numArray[j];
i = j-1;
while(i>=0 && numArray[i] > num)
{
numArray[i+1] = numArray[i];
i--;
}
numArray[i+1] = num;
}
}
int main()
{
int choice;
cout << "1) Insertion Sort" << endl;
cout << "Enter your choice: " << endl;
cin >> choice; // Input choice for which algorithm to use
if(choice == 1)
{
cout << "Enter size of the array: ";
cin >> numArraySize;
int *numbers = new int[numArraySize];
inputNums(numbers); // Insert numbers
insertionSort(numbers); // Use algorithm to sort then output
outputNums(numbers);
}
cout << endl;
system("pause");
return 0;
}
感谢您的帮助:)
【问题讨论】:
-
这是一个学术问题还是您正在处理遗留代码?我认为您没有理由不使用为您管理所有内容的标准容器。
-
只要有例如
void inputNums(int numArray[])- 不需要&-reference。另外,通常认为更好的做法是避免全局变量并传递函数需要操作的值,如void inputNums(int numArray[], int numArraySize)。而且,您应该检查流输入是否有效——如果用户在您等待数字时输入“x”怎么办?试试if (!(cin >> numArray[x])) { std::cerr << "got a non-numeric input, exiting\n"; exit(EXIT_FAILURE); } -
您遇到了什么问题?
-
您应该发布错误或您遇到的任何问题。
标签: c++ arrays pointers pass-by-reference insertion-sort