| CARVIEW |
Select Language
HTTP/2 200
date: Tue, 30 Dec 2025 16:19:31 GMT
content-type: text/html; charset=utf-8
server: cloudflare
last-modified: Mon, 05 Jul 2021 23:22:32 GMT
vary: Accept-Encoding
access-control-allow-origin: *
nel: {"report_to":"cf-nel","success_fraction":0.0,"max_age":604800}
expires: Tue, 30 Dec 2025 16:29:31 GMT
cache-control: max-age=600
report-to: {"group":"cf-nel","max_age":604800,"endpoints":[{"url":"https://a.nel.cloudflare.com/report/v4?s=YRgMor9Rv6kCRzdzOEa0iaHLX3ZxkN55QIR93JO6xP%2BOYXb%2BGKGYxTx3EE00raLCnN3hh46nSXCZPfx3oaZRIIp5u%2Fof0l1i4YfrLFo0Xg%3D%3D"}]}
x-proxy-cache: MISS
x-github-request-id: 2681:33F3E7:60F5940:6CE690E:6953FB92
cf-cache-status: DYNAMIC
content-encoding: gzip
cf-ray: 9b62dbf3e9f3ff60-BOM
alt-svc: h3=":443"; ma=86400
Sort a range of elements - C++ Patterns
← Patterns
Sort a range of elements
1234567891011121314 | #include <array>
#include <algorithm>
#include <iterator>
#include <functional>
int main()
{
std::array<int, 5> arr = {3, 4, 1, 5, 2};
std::sort(std::begin(arr), std::end(arr));
std::sort(std::begin(arr), std::end(arr),
std::greater<int>{});
} |
This pattern is licensed under the CC0 Public Domain Dedication.
Requires
c++11
or newer.
Intent
Sort elements in a range into a given order.
Description
On line 8, we create a std::array of ints
that we wish to sort.
On line 10, we call the standard alrogithm
std::sort, which sorts the range of
elements between the given pair of iterators. We use
std::begin and
std::end to get the begin and end iterators
for the array.
By default, std::sort uses operator< to sort the range, which
arranges the elements in ascending order. It can, however, be
passed a comparison function object to use when comparing
elements. On lines 12–13, we pass an object of type
std::greater<int>, which is a
comparison function object that uses operator>. Accordingly, this
sorts the array in descending order.