Skip to content

Instantly share code, notes, and snippets.

@insaneyilin
Created January 1, 2021 02:39
Show Gist options
  • Save insaneyilin/85591d0fff0932b8cc64005d6a7123bc to your computer and use it in GitHub Desktop.
Save insaneyilin/85591d0fff0932b8cc64005d6a7123bc to your computer and use it in GitHub Desktop.
C++ std::make_heap() std::push_heap() std::pop_heap() example
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
void print_vec(std::vector<int> &vec) {
for (auto x : vec) {
std::cout << x << " ";
}
std::cout << "\n";
}
int main(int argc, char **argv) {
std::vector<int> vec = {10, 5, 2, 11, 8, 3, 5, 9, 0, -2, 20};
print_vec(vec);
std::make_heap(vec.begin(), vec.end());
print_vec(vec);
// std::vector::push_back(), then std::push_heap()
vec.push_back(3);
std::push_heap(vec.begin(), vec.end());
print_vec(vec);
vec.push_back(4);
std::push_heap(vec.begin(), vec.end());
print_vec(vec);
vec.push_back(1);
std::push_heap(vec.begin(), vec.end());
print_vec(vec);
vec.push_back(2);
std::push_heap(vec.begin(), vec.end());
print_vec(vec);
vec.push_back(5);
std::push_heap(vec.begin(), vec.end());
print_vec(vec);
// std::pop_heap(), then std::vector::pop_back()
std::pop_heap(vec.begin(), vec.end());
vec.pop_back();
print_vec(vec);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment