c++ - 打印数组的 C++ 函数
问题描述
我正在尝试编写一个小程序,我想打印数组,但它不起作用,对于应用程序,我使用的是 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
推荐阅读
- html - 链接带有重音符号的文件夹中的 .avi 文件时出错
- c# - UWP 实现 ShyHeader
- django - Django APIClient 测试用例返回 400 但邮递员工作
- amqp - 使用 Qpid 的 AmqpRejectAndDontRequeueException 后重新排队的消息
- c# - SQLCLR 似乎没有启动 Windows 应用程序
- html - 亮度()函数和 preserve-3d 不能一起工作
- javascript - 在页面加载之前使用 JS 加载深色主题
- html - Wget 使用完整的域链接递归获取
- c - 关于带动态指针的 malloc() 和 free()
- python - 在 Django 模板中显示数据库图像时如何修复“TypeError:join()”