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