C++ 로 문자열 길이별 정렬

C++Beginner
지금 연습하기

소개

이 랩에서는 C++ 프로그래밍 언어에서 사용자 정의 정렬 방식을 사용하여 문자열을 길이에 따라 정렬하는 방법을 배우게 됩니다. 또한 사용자 정의 정렬 로직을 구현하고 정렬되지 않은 집합 (unordered set) 의 요소를 특정 순서로 정렬하는 방법도 배우게 됩니다.

새 파일 생성

첫 번째 단계는 새 파일을 생성하는 것입니다. 터미널을 열고 ~/project 디렉토리로 이동합니다. 선호하는 텍스트 편집기를 사용하여 main.cpp라는 새 파일을 생성합니다.

cd ~/project
touch main.cpp

코드 작성

다음 코드를 main.cpp 파일에 추가합니다. 이 코드는 문자열 집합을 길이에 따라 정렬합니다.

#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 LabEx :-)\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;
}

코드 컴파일 및 실행

이 코드를 컴파일하려면 터미널에서 ~/project 디렉토리로 이동하여 다음 명령을 실행합니다.

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

출력 결과는 정렬된 문자열 목록을 보여줍니다.

요약

이 랩에서는 C++ 프로그래밍 언어에서 사용자 정의 정렬 메서드를 작성하여 문자열의 unordered set 을 정렬하는 방법을 배웠습니다. 또한 사용자 정의 정렬 로직을 구현하고 unordered set 의 요소를 특정 순서로 정렬하는 방법도 배웠습니다. 이 지식은 광범위한 프로그래밍 프로젝트에 적용하여 효율적이고 읽기 쉬운 코드를 만드는 데 도움이 될 수 있습니다.