10亿个浮点数,求出其中最大的10000个.

本文介绍了一种利用堆结构高效维护固定大小最大堆的方法,通过不断替换最小元素并重新调整堆来确保堆中始终保存最大的10000个浮点数。此方法适用于实时更新大量数据场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



#include "stdafx.h"
#include <vector>
#include <iostream>
#include <algorithm>
#include <functional> // for greater<>
using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
  vector<float> bigs(10000,0);
  vector<float>::iterator it;


  // Init vector data
  for (it = bigs.begin(); it != bigs.end(); it++)
  {
    *it = (float)rand()/7; // random values;
  }


  cout << bigs.size() << endl;


  make_heap(bigs.begin(),bigs.end(), greater<float>()); // The first one is the smallest one!


  float ff;
  for (int i = 0; i < 1000000000; i++)
  {
    ff = (float) rand() / 7;
    if (ff > bigs.front()) // replace the first one ?
    {
      // set the smallest one to the end!
      pop_heap(bigs.begin(), bigs.end(), greater<float>()); 


      // remove the last/smallest one
      bigs.pop_back(); 


      // add to the last one
      bigs.push_back(ff); 


      // mask heap again, the first one is still the smallest one
      push_heap(bigs.begin(),bigs.end(),greater<float>());
    }
  }


  // sort by ascent
  sort_heap(bigs.begin(), bigs.end(), greater<float>()); 


  // sort by descent
  //sort_heap(bigs.begin(), bigs.end()); 
  //sort_heap(bigs.begin(), bigs.end(), less<float>()); 


  return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值