• 获得最小的topK


    set、multiset都是集合类,差别在与set中不允许有重复元素,multiset中允许有重复元素。
    sets和multiset内部以平衡二叉树实现


    #include<iostream> #include <stdio.h> #include <stack> #include <vector> #include <set> using namespace std; typedef multiset<int, greater<int> > intSet; typedef multiset<int, greater<int> >::iterator setIterator; void get_least_numbers(const vector<int>& data, intSet& least_numbers, int k) { least_numbers.clear(); if (k < 1 || data.size() < k) { return; } vector<int>::const_iterator iter = data.begin(); for(; iter != data.end(); iter++) { if (least_numbers.size() < k) { least_numbers.insert(*iter); } else { setIterator iter_greatest = least_numbers.begin(); if (*iter < *(least_numbers.begin())) { least_numbers.erase(iter_greatest); least_numbers.insert(*iter); } } } } int main() { int a[8] = {4, 2, 6, 7, 9, 5, 1, 3}; int length = sizeof(a) / sizeof(a[0]); const vector<int> data(a, a+length); multiset<int, greater<int> > least_numbers; get_least_numbers(data, least_numbers, 3); for(setIterator it=least_numbers.begin(); it != least_numbers.end(); it++) { cout << *it << " " << endl; } return 0; }
  • 相关阅读:
    Fabric quickly
    jumpserver install
    Docker installs
    快速安装测试版Mysql
    centos7 usually use
    Mysql 通过frm&ibd 恢复数据
    GIT 常用方法
    诸葛亮-诫外甥书
    闭包函数(绑定函数)
    形参和实参
  • 原文地址:https://www.cnblogs.com/TMatrix52/p/12658569.html
Copyright © 2020-2023  润新知