std::sort


Function: std::sort

std::sort is a powerful algorithm provided by the C++ Standard Library that efficiently sorts elements in a container. It's part of the <algorithm> header and offers a versatile way to arrange elements in ascending or descending order, or according to a custom comparison function. Let's explore various examples of using std::sort in different scenarios.

Example 1: Basic Usage with Integers

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

int main() {
    std::vector<int> numbers = {5, 2, 8, 1, 9, 3, 7, 4, 6};

    std::sort(numbers.begin(), numbers.end());

    std::cout << "Sorted numbers: ";
    for (const auto& num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    return 0;
}

Explanation

This example demonstrates the basic usage of std::sort with a vector of integers. The function sorts the elements in ascending order by default.

Example 2: Sorting Strings

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

int main() {
    std::vector<std::string> fruits = {"apple", "banana", "cherry", "date", "elderberry"};

    std::sort(fruits.begin(), fruits.end());

    std::cout << "Sorted fruits: ";
    for (const auto& fruit : fruits) {
        std::cout << fruit << " ";
    }
    std::cout << std::endl;

    // Sorting in descending order
    std::sort(fruits.rbegin(), fruits.rend());

    std::cout << "Reverse sorted fruits: ";
    for (const auto& fruit : fruits) {
        std::cout << fruit << " ";
    }
    std::cout << std::endl;

    return 0;
}

Explanation

This example shows how to sort strings and also demonstrates reverse sorting.

Example 3: Custom Comparison Function

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

struct Person {
    std::string name;
    int age;
};

bool compareByAge(const Person& a, const Person& b) {
    return a.age < b.age;
}

int main() {
    std::vector<Person> people = {
        {"Alice", 30},
        {"Bob", 25},
        {"Charlie", 35},
        {"David", 28}
    };

    std::sort(people.begin(), people.end(), compareByAge);

    std::cout << "Sorted by age:" << std::endl;
    for (const auto& person : people) {
        std::cout << person.name << ": " << person.age << std::endl;
    }

    return 0;
}

Explanation

This example demonstrates using a custom comparison function with std::sort.

Example 4: Sorting with Lambda Functions

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

int main() {
    std::vector<std::pair<std::string, int>> items = {
        {"apple", 5},
        {"banana", 2},
        {"cherry", 8},
        {"date", 1}
    };

    // Sort by the second element of the pair (the integer)
    std::sort(items.begin(), items.end(), 
              [](const auto& a, const auto& b) { return a.second < b.second; });

    std::cout << "Sorted by quantity:" << std::endl;
    for (const auto& item : items) {
        std::cout << item.first << ": " << item.second << std::endl;
    }

    return 0;
}

Explanation

This example shows how to use a lambda function with std::sort.

Example 5: Partial Sorting

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

int main() {
    std::vector<int> numbers = {5, 2, 8, 1, 9, 3, 7, 4, 6};

    // Sort only the first 5 elements
    std::partial_sort(numbers.begin(), numbers.begin() + 5, numbers.end());

    std::cout << "Partially sorted numbers: ";
    for (const auto& num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    return 0;
}

Explanation

This example demonstrates std::partial_sort, a variation of std::sort that sorts only a portion of the container.

Summary

std::sort is a versatile algorithm in C++ for sorting elements in containers. We've explored its usage in various scenarios:

  1. Basic sorting of integers in ascending order.
  2. Sorting strings and demonstrating reverse sorting.
  3. Using custom comparison functions to sort complex objects.
  4. Employing lambda functions for flexible, inline comparisons.
  5. Partial sorting with std::partial_sort.

These examples showcase the flexibility and power of std::sort. It can handle different data types, custom objects, and various sorting criteria. The algorithm's efficiency (typically O(n log n) complexity) makes it suitable for sorting large datasets. Remember that std::sort modifies the original container, so if you need to preserve the original order, consider making a copy before sorting.

Related

Previous Page | Course Schedule | Course Content