我们如何获得传递给函数的数组的大小?
How can we get the size of an array that is passed into the function?
这是我的程序,有人能告诉我如何在不将其传递给函数的情况下获得 '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);
}
当然你总是可以使用模板:
#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);
}
这是我的程序,有人能告诉我如何在不将其传递给函数的情况下获得 '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);
}
当然你总是可以使用模板:
#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);
}