堆的插入/删除/打印操作
#include<iostream> #include<vector> #include<math.h> using namespace std; //堆的插入 vector<int> insert(int x,vector<int> heap) { int temp; if(heap.empty()) { heap.push_back(x); } else { heap.push_back(x); for(int i=heap.size();heap[i/2-1]>heap[i-1];i=i/2) { temp=heap[i-1]; heap[i-1]=heap[i/2-1]; heap[i/2-1]=temp; if(i==0)break; } } return heap; } //删除堆中的最小元素 vector<int> delete_element(vector<int> heap) { vector<int> temp; vector<int> heap_new; for(int i=1;i<heap.size();i++) temp.push_back(heap[i]); for(int j=0;j<temp.size();j++) { heap_new=insert(temp[j],heap_new); } return heap_new; } //堆元素的打印 void print_heap(vector<int> heap) { int count=1; if(heap.empty()) cout<<"this heap is empty!"<<endl; else { for(int i=0;i<heap.size();i++) { cout<<heap[i]<<" "; if((i+2)==pow(2,count)) { cout<<endl; count++; } } } cout<<endl; } int main() { //创建一个空堆 vector<int> heap; int x; char c; while(cin>>x) { heap=insert(x,heap); c=cin.get(); if(c==' ') break; } print_heap(heap); vector<int> heap2; heap2=delete_element(heap); print_heap(heap2); return 0; }