Sorting Strings by Length in C++

C++C++Beginner
Practice Now

Introduction

In this lab, you will learn how to sort strings based on length using a custom sort method in the C++ programming language. You will also learn how to implement custom sorting logic and order the elements of an unordered set in a specific order.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("`C++`")) -.-> cpp/SyntaxandStyleGroup(["`Syntax and Style`"]) cpp(("`C++`")) -.-> cpp/BasicsGroup(["`Basics`"]) cpp(("`C++`")) -.-> cpp/ControlFlowGroup(["`Control Flow`"]) cpp(("`C++`")) -.-> cpp/FunctionsGroup(["`Functions`"]) cpp/SyntaxandStyleGroup -.-> cpp/comments("`Comments`") cpp/BasicsGroup -.-> cpp/variables("`Variables`") cpp/BasicsGroup -.-> cpp/data_types("`Data Types`") cpp/BasicsGroup -.-> cpp/operators("`Operators`") cpp/BasicsGroup -.-> cpp/booleans("`Booleans`") cpp/ControlFlowGroup -.-> cpp/conditions("`Conditions`") cpp/ControlFlowGroup -.-> cpp/for_loop("`For Loop`") cpp/FunctionsGroup -.-> cpp/function_parameters("`Function Parameters`") subgraph Lab Skills cpp/comments -.-> lab-96224{{"`Sorting Strings by Length in C++`"}} cpp/variables -.-> lab-96224{{"`Sorting Strings by Length in C++`"}} cpp/data_types -.-> lab-96224{{"`Sorting Strings by Length in C++`"}} cpp/operators -.-> lab-96224{{"`Sorting Strings by Length in C++`"}} cpp/booleans -.-> lab-96224{{"`Sorting Strings by Length in C++`"}} cpp/conditions -.-> lab-96224{{"`Sorting Strings by Length in C++`"}} cpp/for_loop -.-> lab-96224{{"`Sorting Strings by Length in C++`"}} cpp/function_parameters -.-> lab-96224{{"`Sorting Strings by Length in C++`"}} end

Create a new file

The first step is to create a new file. Open a terminal and navigate to the ~/project directory. Create a new file called main.cpp using your preferred text editor.

cd ~/project
touch main.cpp

Write the code

Add the following code to the main.cpp file. This code will sort a set of strings based on their length.

#include <iostream>
#include <bits/stdc++.h>

using namespace std;

//Returns true if the first string is of longer length than the second
bool cmp(string x, string y)
{
    int n = x.length();
    int m = y.length();

    if (n > m)
        return true;
    else
        return false;
}

//Function to print the elements of the unordered set using an iterator
void show(unordered_set<string> s)
{
    //declaring an iterator to iterate through the unordered set
    unordered_set<string>::iterator i;

    for (i = s.begin(); i != s.end(); i++)
    {
        cout << *i << "     "; //accessing the elements of the unordered set using * as i stores the address to each element
    }

    cout << endl;
}

int main()
{
    cout << "\n\nWelcome to Studytonight :-)\n\n\n";
    cout << " =====  Program to demonstrate the Sorting Strings on the basis of length, in CPP  ===== \n\n\n\n";

    cout << " *** Unordered Set automatically removes the duplicate elements and maintains a random ordering. *** \n\n";

    cout << " *** This random ordering depends on the hash function that is used internally. *** \n\n";

    cout << " *** Unordered set can be sorted by copying its elements to a Vector. *** \n\n";

    //Unordered Set declaration (Unordered Set of strings)
    unordered_set<string> s;

    //Filling the elements by using the insert() method.
    cout << "\n\nFilling the Unordered Set with strings in random order."; //Unlike Set, this is not automatically sorted

    s.insert("Study");
    s.insert("Tonight");
    s.insert("Aditya");
    s.insert("Abhishek");
    s.insert("C++");
    s.insert("Hi");

    cout << "\n\nThe elements of the Unordered Set before sorting are:\n ";
    show(s);

    //Declaring a vector and initializing it with the elements of the unordered set
    vector<string> v(s.begin(), s.end());

    //Sorting the vector elements in descending order of their length using a custom comparator
    sort(v.begin(), v.end(), cmp);

    cout << "\n\nThe elements of the Unordered Set after sorting in descending Order of their length using a custom comparator are: \n";

    //declaring an iterator to iterate through the vector
    vector<string>::iterator it;

    for (it = v.begin(); it != v.end(); it++)
    {
        cout << *it << "     "; //accessing the elements of the vector using * as i stores the address to each element
    }

    cout << "\n\n\n";

    return 0;
}

Compile and run the code

To compile this code, navigate to the ~/project directory in the terminal, and run the following command:

g++ main.cpp -o main && ./main

The output will show you the sorted list of strings.

Summary

In this lab, you learned how to sort an unordered set of strings by writing a custom sort method in the C++ programming language. You also learned how to implement custom sorting logic and order the elements of an unordered set in a specific order. This knowledge can be applied to a wide range of programming projects, helping you create code that is efficient and easy to read.

Other C++ Tutorials you may like