首页 > 解决方案 > 我们如何获得传递给函数的数组的大小?

问题描述

这是我的程序,有人可以告诉我如何在不将其传递给函数的情况下在这里获得正确的“n”值(数组的大小)吗?

#include <iostream>
using namespace std;

char * findFrequency (int input1[],int input2)
{
    int n = sizeof(input1) / sizeof(input1[0]);
    
    int count = 0;
    for(int i = 0; i < n; i++)
    {
        if(input1[i] == input2) 
         count++;
    }
    string ch;
    if(count == 0) 
     ch = to_string(input2) + " not present"; 
    else 
     ch = to_string(input2) + " comes " + to_string(count) + " times";
    std::cout << ch << "\nn = " << n;
}
int main ()
{
    int a[] = {1, 1, 3, 4, 5, 6};
    findFrequency(a, 1);
}

标签: c++arrayssize

解决方案


当然,您始终可以使用模板:

#include <iostream>
using namespace std;

template<typename T, std::size_t N>
void findFrequency (T(&input1)[N], int input2)
{
    // input1 is the array
    // N is the size of it

    //int n = sizeof(input1) / sizeof(input1[0]);

    int count = 0;
    for(int i = 0; i < N; i++)
    {
        if(input1[i] == input2)
         count++;
    }
    string ch;
    if(count == 0)
     ch = to_string(input2) + " not present";
    else
     ch = to_string(input2) + " comes " + to_string(count) + " times";
    std::cout << ch << "\nn = " << N;
}
int main ()
{
    int a[] = {1, 1, 3, 4, 5, 6};
    findFrequency(a, 1);
}

推荐阅读