Sorting in C++

Our example demonstrates sorting in C++. We’ll use the standard library’s sorting functions for built-in types.

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

int main() {
    // Sorting functions work for any container that provides random-access iterators
    // and are compatible with various types, including built-in types.

    std::vector<std::string> strs = {"c", "a", "b"};
    std::sort(strs.begin(), strs.end());
    std::cout << "Strings: ";
    for (const auto& s : strs) {
        std::cout << s << " ";
    }
    std::cout << std::endl;

    // An example of sorting ints.
    std::vector<int> ints = {7, 2, 4};
    std::sort(ints.begin(), ints.end());
    std::cout << "Ints:    ";
    for (const auto& i : ints) {
        std::cout << i << " ";
    }
    std::cout << std::endl;

    // We can also use the standard library to check if a container is already in sorted order.
    bool s = std::is_sorted(ints.begin(), ints.end());
    std::cout << "Sorted:  " << (s ? "true" : "false") << std::endl;

    return 0;
}

To compile and run the program:

$ g++ -std=c++11 sorting.cpp -o sorting
$ ./sorting
Strings: a b c
Ints:    2 4 7
Sorted:  true

In this C++ version, we use the <algorithm> header which provides sorting and other useful functions. The std::sort function is used to sort the containers, and std::is_sorted checks if a container is already sorted.

Note that C++ sorting functions work with iterators, which allows them to be used with various container types, not just vectors. The sorting is done in-place, modifying the original container.

C++ provides a rich set of algorithms in the standard library, making it easy to perform operations like sorting on different types of data structures.