(C++) std::sort\_heap
January 11, 2018 · View on GitHub
(C++) std::sort_heap
std::sort_heap is an STL heap algorithm to rearrange the elements in container from a heap to a sorted sequence.
#include <algorithm> #include <iostream> #include <vector> #include <boost/foreach.hpp> int main () { std::vector<int> v; v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(4); v.push_back(5); std::cout << "Initial std::vector: "; BOOST_FOREACH(int i, v) std::cout << i << ' '; std::make_heap(v.begin(),v.end()); std::cout << "\nstd::vector after std::make_heap: "; BOOST_FOREACH(int i, v) std::cout << i << ' '; v.push_back(10); std::push_heap(v.begin(),v.end()); std::cout << "\nstd::vector after std::push_heap of 10: "; BOOST_FOREACH(int i, v) std::cout << i << ' '; std::pop_heap(v.begin(),v.end()); v.pop_back(); std::cout << "\nstd::vector after std::pop_heap (which removes the heighest value): "; BOOST_FOREACH(int i, v) std::cout << i << ' '; std::sort_heap(v.begin(),v.end()); std::cout << "\nstd::vector after std::sort_heap: "; BOOST_FOREACH(int i, v) std::cout << i << ' '; }
Screen output:
Initial std::vector: 1 2 3 4 5 std::vector after std::make_heap: 5 4 3 1 2 std::vector after std::push_heap of 10: 10 4 5 1 2 3 std::vector after std::pop_heap (which removes the heighest value): 5 4 3 1 2 std::vector after std::sort_heap: 1 2 3 4 5