C++函数打印数组

C++ functions printing an array

本文关键字:数组 打印 函数 C++      更新时间:2023-10-16

>我正在尝试编写一个小程序,我想打印数组,但它不起作用,对于应用程序,我正在使用 case 函数。

构建一个交互式应用程序,在屏幕上显示五个选项:

读取一串数值;

  • 显示字符串;
  • 使用插入排序对字符串进行排序;
  • 使用按选择排序对字符串进行排序;
  • 使用排序气泡排序对字符串进行排序;
  • 退出应用程序。

这是我当前的代码:

#include <iostream>
using namespace std;
// int n[12] = {1, 2, 3, 4, 5, 6, 15, 18, 57, 30, 20, 7};
int j, k, nr, n[20];
void values(void) {
cout << "n"
<< "input_values ";
int n[20], nr, i;
cout << "number of elements max 20 ";
cin >> nr;
for (i = 0; i < nr; i++) {
cout << "n[" << i << "] = ";
cin >> n[i];
}
}
void afisare(void) {
cout << "n"
<< "display array; ";
for (int i = 0; i < nr; ++i)
cout << n[i] << ",";
}

在这种情况下,您可以使用function pointer,例如:

void sort1(int*arr, int n);
void sort2(int*arr, int n);
void sort3(int*arr, int n);
void show(int*arr, int n);
//...
//implement body for the functions above
//...
int main()
{
int arr[5]={5,4,6,3,9};
int n=5;
void (*funcPointer[4])(int*,int)={&sort1,&sort2,&sort3,&show};
int choice=999;
//assume you just type from -1 to 3.
//-1 means exit
while(choice!=-1)
{
cin>>choice;
if(choice==-1) //exit
{
return 0;
}
else
{
funcPointer[choice](arr,n); 
}
//and do something what you want
}
return 0;
}

查看更多关于function pointer的信息 https://www.cprogramming.com/tutorial/function-pointers.html