はじめに
この実験では、C++ プログラミング言語を使ってカスタムソートメソッドを使って文字列の長さに基づいてソートする方法を学びます。また、カスタムソートロジックを実装し、特定の順序で無順序セットの要素を並べる方法も学びます。
この実験では、C++ プログラミング言語を使ってカスタムソートメソッドを使って文字列の長さに基づいてソートする方法を学びます。また、カスタムソートロジックを実装し、特定の順序で無順序セットの要素を並べる方法も学びます。
最初の手順は、新しいファイルを作成することです。ターミナルを開き、~/project
ディレクトリに移動します。好きなテキストエディタを使って main.cpp
という名前の新しいファイルを作成します。
cd ~/project
touch main.cpp
main.cpp
ファイルに以下のコードを追加します。このコードは、文字列のセットをその長さに基づいてソートします。
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
//最初の文字列の長さが2番目の文字列より長い場合、trueを返す
bool cmp(string x, string y)
{
int n = x.length();
int m = y.length();
if (n > m)
return true;
else
return false;
}
//イテレータを使って無順序セットの要素を表示する関数
void show(unordered_set<string> s)
{
//無順序セットを反復処理するためのイテレータを宣言
unordered_set<string>::iterator i;
for (i = s.begin(); i!= s.end(); i++)
{
cout << *i << " "; //iが各要素のアドレスを格納しているため、*を使って無順序セットの要素にアクセス
}
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<string> s;
//insert()メソッドを使って要素を追加する
cout << "\n\nFilling the Unordered Set with strings in random order."; //Setとは異なり、これは自動的にソートされない
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);
//ベクトルを宣言し、無順序セットの要素で初期化する
vector<string> v(s.begin(), s.end());
//カスタムコンパレータを使ってベクトル要素を長さの降順にソートする
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";
//ベクトルを反復処理するためのイテレータを宣言
vector<string>::iterator it;
for (it = v.begin(); it!= v.end(); it++)
{
cout << *it << " "; //iが各要素のアドレスを格納しているため、*を使ってベクトルの要素にアクセス
}
cout << "\n\n\n";
return 0;
}
このコードをコンパイルするには、ターミナルで ~/project
ディレクトリに移動し、次のコマンドを実行します。
g++ main.cpp -o main && ./main
出力には、ソートされた文字列のリストが表示されます。
この実験では、C++ プログラミング言語を使ってカスタムソートメソッドを書くことで、文字列の無順序セットをソートする方法を学びました。また、カスタムソートロジックを実装し、特定の順序で無順序セットの要素を並べる方法も学びました。この知識は幅広いプログラミングプロジェクトに適用でき、効率的で読みやすいコードを作成するのに役立ちます。