C++ 统计数组中元素的出现次数

1.获取数组长度

参考 https://www.cnblogs.com/tanrong/p/8516948.html
在这里插入图片描述

2.统计次数

以C++程序为例

#include <iostream>
using namespace std;

template <class T>

int getArrayLen(T& array){
    //使用模板定义一 个函数getArrayLen,该函数将返回数组array的长度
    return (sizeof(array) / sizeof(array[0]));
}

int main(){

    int a[] = {1,2,3,4,4,3};
    //cout << getArrayLen(a) << endl;

    //一次遍历,统计每个值出现的次数
    int len=0,i=0,j=0,temp=0;
    int count [10000];

    len = getArrayLen(a);
    for (i = 0;i < len;i++){
        temp  = a[i];
        count[temp]++;  //66666  
    }  
    for(j = 1;j <= len;j++){
        cout << count[j] << endl;
    }

    return 0;
}
发布了49 篇原创文章 · 获赞 7 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/knaha/article/details/95076841