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

来源:互联网 发布:mac ae2017中英文切换 编辑:程序博客网 时间:2024/05/16 21:31


#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;
}

原创粉丝点击