c++ - 我们如何获得传递给函数的数组的大小?
问题描述
这是我的程序,有人可以告诉我如何在不将其传递给函数的情况下在这里获得正确的“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);
}
推荐阅读
- gnuplot - 在 gnuplot 中循环 - 不同的文件夹
- android - Viewpager 中的片段没有向上滚动
- git - GIT:如何取消加入两个分支的合并
- python - 导入包魅力:没有名为魅力的模块
- java - 为什么 System.out.print(ternary operator) 在输出中打印浮点数?
- javascript - 如何使用切片删除最后一个元素并将包含所有单词和“/:”的链接拆分为一个链接?
- java - 以编程方式禁用 android 安全键盘保护
- java - 在集合框架上,Java 提供了 Queue ,它也可以被 List 模仿。Queue 的独特用途是什么?
- node.js - node js如何通过发送数据调用webapi(x-www-form-urlencoded)
- reactjs - 将css导入react js