Blog Archive

Wednesday, April 10, 2019

[how to remember] priority_queue vs sort



https://coliru.stacked-crooked.com/view?id=27147c4921124ec6

http://www.cplusplus.com/reference/algorithm/sort/

#include <functional>
#include <queue>
#include <vector>
#include <iostream>
bool myfunction (int left, int right) { return (left ) < (right);}
//auto cmp = [](int left, int right) { return left < right;};
auto cmp = [](int  left, int head) { return left < head;}; 
// head is 1st come out of priority_queue; left is what is left
template<typename T> void print_queue(T& q) {
    while(!q.empty()) {
        std::cout << q.top() << " ";
        q.pop();
    }
    std::cout << '\n';
}

int main() {
    std::priority_queue<int> q;

    for(int n : {1,8,5,6,3,4,0,9,7,2})
        q.push(n);

    print_queue(q);

    std::priority_queue<int, std::vector<int>, std::greater<int> > q2;

    for(int n : {1,8,5,6,3,4,0,9,7,2})
        q2.push(n);

    print_queue(q2);

    // Using lambda to compare elements.
    //auto cmp = [](int left, int right) { return (left ^ 1) < (right ^ 1);};
    //auto cmp = [](int left, int right) { return (left ) < (right);};

    std::priority_queue<int, std::vector<int>, decltype(cmp)> q3(cmp);

    for(int n : {1,8,5,6,3,4,0,9,7,2})
        q3.push(n);

    print_queue(q3);
    std::vector<int> ivec({1,8,5,6,3,4,0,9,7,2});
   
    sort(ivec.begin(), ivec.end(), myfunction);
    for(std::vector<int>::iterator it=ivec.begin(); it!=ivec.end(); it++){
       std::cout<<*it<<" ";
    }
    std::cout<<std::endl;

}

g++ -std=c++2a -pthread -fgnu-tm  -O2 -Wall -Wextra -pedantic -pthread -pedantic-errors main.cpp -lm  -latomic -lstdc++fs  && ./a.out
9 8 7 6 5 4 3 2 1 0 
0 1 2 3 4 5 6 7 8 9 
9 8 7 6 5 4 3 2 1 0 
0 1 2 3 4 5 6 7 8 9 

No comments:

Post a Comment