首页 > 解决方案 > 打印数组的 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] << ",";
}

标签: c++arraysfunction

解决方案


您可以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


推荐阅读