例如输入1,2,3,4,5,6,7 和8 这8 个数字,则最小的4 个数字为1,2,3 和4。
答案:
//20121124
#include <iostream> #include <algorithm> #include <vector> #include <functional> using namespace std; int main() { int k; cout<<"Type in the K you want"<<endl; cin>>k; int n=0; char c; vector<int> vi; while (1) { cin>>c; if (c=='#') { break; } n=c-0x30; if (vi.size()<k) { vi.push_back(n); } else { make_heap(vi.begin(),vi.end(),greater<int>()); if (n<vi[k-1]) { vi.pop_back(); vi.push_back(n); } } } cout<<"The K min:"<<endl; make_heap(vi.begin(),vi.end()); sort_heap(vi.begin(),vi.end()); vector<int>::iterator itor,endor; endor=vi.end(); for (itor=vi.begin();itor!=endor;itor++) { cout<<*itor<<" "; } return 0; }