algorithms/sort/prog-2-kn.cpp - Sorting a vector of integers. | Lecture 6 - slide 22 : 40 Program 1 |
// sort algorithm example - adapted from www.cplusplus.com #include <iostream> // std::cout #include <algorithm> // std::sort #include <vector> // std::vector template<typename Cont> void print_container(Cont c); bool myfunction (int i,int j) { return (i<j); } struct myclass { bool operator() (int i,int j) { return (i<j);} }; int main () { int myints[] = {32,71,12,45,26,80,53,33}; std::vector<int> myvector (myints, myints+8); print_container(myvector); // 32 71 12 45 26 80 53 33 // using default comparison (operator <): std::sort(myvector.begin(), myvector.begin()+4); print_container(myvector); // (12 32 45 71)26 80 53 33 // using function for comparison: std::sort(myvector.begin()+4, myvector.end(), myfunction); print_container(myvector); // 12 32 45 71(26 33 53 80) // using an object of type myclass for comparison: std::sort(myvector.begin(), myvector.end(), myclass{}); print_container(myvector); // 12 26 32 33 45 53 71 80 // using a lambda expression for comparison - descending order! std::sort(myvector.begin(), myvector.end(), [](const int &i, const int &j){return j < i;}); print_container(myvector); // 80 71 53 45 33 32 26 12 return 0; } template<typename Cont> void print_container(Cont c){ for(auto el: c) std::cout << ' ' << el; std::cout << std::endl; }