Exploring Sorting Techniques in C++

Lesson Introduction and Overview

Hello, and welcome back! Our journey today takes us into the sorting universe in C++. We will learn about and utilize the built-in sorting function from the C++ Standard Library: std::sort. This tool significantly simplifies the task of sorting in C++. Let's get started!

Understanding Sorting and Its Importance

Sorting refers to arranging data in a specific order, which enhances the efficiency of search or merge operations on data. In real life, we sort books alphabetically or clothes by size. Similar concepts apply in programming, where sorting large lists of data is essential for more effective analysis.

C++ offers a built-in sorting method: std::sort, found in the <algorithm> header. Here's a demonstration of how we use this method:

Sorting of Primitive Types and Objects

Sorting with std::sort makes sorting arrays and vectors straightforward. Let's see it in action!

Sorting Arrays of Primitives

#include <iostream>
#include <algorithm>

int main() {
    int arr[] = {4, 1, 3, 2};
    std::sort(arr, arr + 4);
    for (int i = 0; i < 4; ++i) {
        std::cout << arr[i] << " ";
    }
    // Output: 1 2 3 4
    return 0;
}

Sorting Vectors of Strings

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

int main() {
    std::vector<std::string> inventory = { "Bananas", "Pears", "Apples", "Dates" };
    std::sort(inventory.begin(), inventory.end());
    for (const auto& item : inventory) {
        std::cout << item << std::endl;
    }

    // Output:
    // Apples
    // Bananas
    // Dates
    // Pears
    return 0;
}

As you can see, sorting in C++ is as simple as that!

More Complex Sorting Problem

C++ allows us to define custom sorting logic using lambda expressions. Let's sort a vector of students by their grades, with alphabetical sorting applied in the event of ties in grades. First, let's define the Student class:

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

class Student {
public:
    std::string Name;
    int Grade;

    Student(std::string name, int grade) : Name(name), Grade(grade) {}

    friend std::ostream& operator<<(std::ostream& os, const Student& s) {
        os << s.Name << ":" << s.Grade;
        return os;
    }
};
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal