CPP STL Tutorial: C++ Sorting operation that can be performed on containers

Below are some of the sorting operations that can be performed on STL containers.
sort : Sort elements in range
stable_sort : Sort elements preserving order of equivalents
partial_sort : Partially sort elements in range
partial_sort_copy : Copy and partially sort range
is_sorted   :Check whether range is sorted
is_sorted_until  : Find first unsorted element in range
nth_element : Sort element in range

Example for sort and stable_sort:

#include <iostream>
#include <vector>
#include <array>
#include <algorithm>    // std::all_of

//for more tutorials on C, C++, STL, DS visit www.ProDeveloperTutorial.com
using namespace std;

bool myfunction (int i,int j) { return (i<j); }


int main () 
{
  std::vector<int> myvector = {3, 2, 1, 5, 8, 7, 0};

  // by using default sort
  std::sort (myvector.begin(), myvector.end()); 

  // using function as comp
  std::sort (myvector.begin(), myvector.end(), myfunction);
  
  std::cout << "myvector in sorted order contains:";
  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';
  
  
  return 0;
}

Output:

myvector in sorted order contains: 0 1 2 3 5 7 8

Example for partial_sort and is_sorted:

#include <iostream>
#include <vector>
#include <array>
#include <algorithm>    // std::all_of

//for more tutorials on C, C++, STL, DS visit www.ProDeveloperTutorial.com
using namespace std;

bool myfunction (int i,int j) { return (i<j); }

int main () 
{
  std::vector<int> myvector = {3, 2, 1, 5, 8, 7, 0};

  // by using default sort
  // using default comparison (operator <):
  std::partial_sort (myvector.begin(), myvector.begin()+3, myvector.end());
  
  std::cout << "myvector in partially sorted order contains:";
  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';
  
  if(std::is_sorted(myvector.begin(),myvector.begin()+3))
    std::cout << "\nthe given range is sorted!\n";
  
  return 0;
}

Output:

myvector in partially sorted order contains: 0 1 2 5 8 7 3

the given range is sorted!

 

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *