如何在C ++中找到数组中重复元素的频率分布?

时间:2018-07-05 15:39:54

标签: c++ arrays algorithm

我已经用C ++编写了一个代码,接受10个卷号的标记并将其存储在2D数组中。如果学生缺席,我们输入666表示敬意。

#include<iostream>
using namespace std;
int main()
{
  int i;
  int a[2][10];
  a[0][0]=0;
  a[1][0]=0;
  cout<<"Enter marks of 10 students. Enter 666 if absent."<<endl;
  for(i=1;i<10;i++)
  {
     a[0][i]=i;
     cin>>a[1][i]; 
  }

  cout<<"The frequency distribution of the marks is : ";
  return 0;
}

现在我想找到重复多少次的模式和频率分布。我该如何实现?

示例数组块: enter image description here

2 个答案:

答案 0 :(得分:1)

这是使用类

的方法
class MarkManager {
public: 
    void addMark(int m) {freqMap[m]+=1;}
    void printStatistics() 
    { 
        for(auto it = freqMap.begin(); it != freqMap.end();++it) 
            std::cout << it->first << ":" << (*it).second << std::endl;
    }
private:
    std::map<int, int> freqMap;
};

int main()
{

    MarkManager markMng; 
    int tmp;
    for(int i=0;i<10;++i)
    {
         cin >> tmp;
         markMng.addMark(tmp);
    }
    markMng.printStatistics();

}

答案 1 :(得分:0)

您可以使用std::map查找密钥是否在地图中,如果存在,则将其计数更新1。

这是您可以尝试的示例代码:

#include <iostream>
#include <map>
using namespace std;

int main()
{
    int array[] = { 7, 666, 7, 8, 8, 7, 666, 5, 5, 5};

    std::map <int, int> freq;

    size_t arrayLength = sizeof(array)/sizeof(array[0]);

    for(size_t i = 0; i < arrayLength; i++)
    {
        if(array[i] == 666) //Skip 666 entries
           continue;

        map<int, int> :: iterator foundIterator; //Iterator for checking found elements
        foundIterator = freq.find(array[i]);

        //If element is not present in Map then set its count to 1
        if(foundIterator == freq.end())
            freq[array[i]] = 1;

        //Else update its count by 1
        else
            freq[array[i]] += 1;
    }

    //Print the Map now    
    map <int, int> :: iterator itr;    
    for(itr = freq.begin(); itr != freq.end(); itr++)
        cout << itr -> first << "\t" << itr -> second << endl;
}