将数组作为引用传递到函数中不起作用

Passing an array as a Reference into a function not working

本文关键字:函数 不起作用 数组 引用      更新时间:2023-10-16

对于我在学校的实验室,我被要求生成随机数字和字符并将其传递到函数模板中,然后在首先显示我的工作未排序后对它们进行排序。我使用视觉工作室作为我学校的要求,但我的主要问题是它的编译没有错误,但是当我运行我的程序时,它没有传递我的数组进行排序。我一直花了很多时间试图理解为什么它不起作用,任何帮助将不胜感激。

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <algorithm>
using namespace std;
template <typename T> 
void arrayIn(T arr[], int size, char word) {
if (word == 'd') {
sort(arr, arr + size, greater<>());
}
else {
sort(arr, arr + size);
}
return;
}
template <typename O> 
void arr_out(O arr[], int size) {
int j;
for (j = 0; j < size; j++) {
cout << arr[j] << endl;
return;
}
delete[] arr;
}
int main(void) {
srand(time_t(NULL));
int size,i,j;
char word;
int *arr1;
char *arr2;

cout << "Enter in the size of the array: ";
cin >> size;
cout << "How would you like to sort in ascending or descending order?: ";
cin >> word;
arr1 = new int[size];
arr2 = new char[size];
if (arr1 == 0) {
cout << "memory allocation error";
system("pause");
exit(1);
}
cout << "The first array will sort intagers." << endl;
cout << "not sorted" << endl;
for (i = 0; i < size; i++) {
arr1[i] = rand() % 100 + 1;
cout << arr1[i] << endl;
}
arrayIn(arr1, size, word);
cout << "sorted" << endl;
arr_out(arr1,size);
if (arr2 == 0) {
cout << "memory allocation error";
system("pause`enter code here`");
exit(1);
}
cout << "the secound array will sort characters." << endl;
cout << "not sorted" << endl;
for (j = 0; j < size; j++) {
arr2[j] = rand() % (126 + 1 - 33) + 33;
cout << arr2[j] << endl;
}
arrayIn(arr2, size, word);
cout << "sorted" << endl;
arr_out(arr2, size);
system("pause");
return 0;
}

你的arr_out函数中有一个非常简单的错误,这使得它只打印第一个元素。更正如下(删除我注释掉的行(:

template <typename O> 
void arr_out(O arr[], int size) {
int j;
for (j = 0; j < size; j++) {
cout << arr[j] << endl;
//  return; // This will return after printing the first element!
}
delete[] arr;
}