c++ - 查找数组中出现次数最多的值和中值 C++

标签 c++ visual-studio-2010

我想使用 C++ 查找给定数组的最频繁值和中值。我假设我有一个 float 组,例如

float *LRArr=new LRArr[1000];

数组由随机 float 填充。

std::default_random_engine generator;
generator.seed( rd() );
std::uniform_real_distribution<> distribution(0, 10);
for(int j=0;j<1000;j++)
{
    LRArr[j]=distribution(generator)
}

现在我想获取数组中最常见的值。但这需要很多时间。你能给我建议用 C 或 C++ 实现它的更快的方法吗?我假设我有 LRArr 例如

LRArr={0.1,1.2,6.5,6.5,4.5,6.5}
==>output is: 6.5 and median 5.5

这是我的方式:

float getMostFreq(float* LRArr;int sizeLRArr)
{
int count = 1;
int currentIndex = 0;
   for (int i = 1; i < sizeLRArr; i++)
   {
    if (LRArr[i] == LRArr[currentIndex])
        count++;
    else
        count--;
    if (count == 0)
    {
        currentIndex = i;
        count = 1;
    }
  }
  mostFreq = LRArr[currentIndex];
  return mostFreq;
} 

最佳答案

计算数组中浮点值频率的一种方法是计算直方图并对其进行排序。但您应该考虑到应定义值的范围。这样,准确性取决于直方图箱的数量:

#include <algorithm>

#define histogramCount 10000
#define upperRange 1000
#define lowerRange 0

class histogram_data
{
public:
  int frequency;
  int index;
};

bool SortPredicate(const histogram_data& d1, const histogram_data& d2)
{
    return d1.frequency> d2.frequency;
}


void computeHistogram(float * array, int len)
{

   std::vector<histogram_data> histogram;

   for(int i=0;i<histogramCount;i++)
   {
       histogram_data hdata;
       hdata.frequency=0;
       hdata.index=i;
       histogram.push_back(hdata);
   }


   for(int i=0;i<len;i++)
   {
       histogram[(array[i]/(upperRange-lowerRange))*(histogramCount-1)].frequency++;
   }

   //sorting the histogram in descending order

    std::sort(histogram.begin(),histogram.end(),SortPredicate);

}

现在值的频率按降序存储在直方图中。因此,最常见的值可以通过以下方式获取:

float mostFrequent = ((float)histogram[0].index/(float)(histogramCount-1))*(upperRange-lowerRange);

关于c++ - 查找数组中出现次数最多的值和中值 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24218377/

相关文章:

c++ - glAccum(模糊效果)适用于一张显卡,但不适用于另一张显卡

c++ - 在 C++ 中从 std::string 转换为 char *

c++ - 如何将方法指针作为模板参数传递

c++ - 从文件中读取十六进制,printf %x 显示前导 ff 值

c++ - Visual Studio 201x 项目设置

c++ - Microsoft Visual C++ 2010 Express 安装/运行问题

c++ - C++ 中的文件 I/O 代码

C# 自定义项目模板

java - 在单向链表中添加双向链表节点

c++ - 如何:Boost::asio 的客户端连接管理器?