std::sort()
is a built-in function in C++'s Standard Template Library. The function takes in a beginning iterator, an ending iterator, and (by default) sorts the iterable in ascending order. The function can also be used for custom sorting by passing in a comparator
function that returns a boolean.
Take a look at the function signature of std::sort()
below:
In the following examples, an array of strings will be sorted:
std::sort()
#include <iostream>// The following library needs to be included to use std::sort()#include <algorithm>using namespace std;int main() {string coffee[] = {"latte", "cappuccino", "americano", "espresso"};int size = 4;std::sort(coffee, coffee + size);for (int i = 0; i < 4; i++){cout<<coffee[i]<<endl;}return 0;}
std::sort()
with a built-in comparator#include <iostream>// The following library needs to be included to use std::sort()#include <algorithm>// The following library needs to be included to use std::greater<datatype>()#include <functional>using namespace std;int main() {string coffee[] = {"latte", "cappuccino", "americano", "espresso"};int size = 4;std::sort(coffee, coffee + size, std::greater<string>());for (int i = 0; i < 4; i++){cout<<coffee[i]<<endl;}return 0;}
std::sort()
with a custom comparator#include <iostream>// The following library needs to be included to use std::sort()#include <algorithm>using namespace std;// Custom comparator to sort in descending orderbool comparator(string &a, string &b){return a > b;}int main() {string coffee[] = {"latte", "cappuccino", "americano", "espresso"};int size = 4;std::sort(coffee, coffee + size, comparator);for (int i = 0; i < 4; i++){cout<<coffee[i]<<endl;}return 0;}
Free Resources