C++
 Computer >> コンピューター >  >> プログラミング >> C++

STLでlexicographical_compare()を実装するためのC++プログラム

lexicographical_compare()関数とは

C++の標準ライブラリ(STL)に含まれる std::lexicographical_compare() は、ある範囲(イテレータで指定されたシーケンス)が、別の範囲と比べて辞書順で小さいかどうかを判定する関数です。辞書順比較とは、辞書で単語をアルファベット順に並べ替える際に用いられる一般的な比較方法のことです。

宣言

template <class InputIterator1, class InputIterator2>
bool lexicographical_compare(InputIterator1 first1, InputIterator1 last1,
                             InputIterator2 first2, InputIterator2 last2);

first1・last1 は1つ目の範囲の先頭と末尾、first2・last2 は2つ目の範囲の先頭と末尾を指すイテレータです。1つ目の範囲が2つ目の範囲よりも辞書順で小さい場合に true を返します。

アルゴリズム

Begin
    result = lexicographical_compare(v1.begin(), v1.end(), v2.begin(), v2.end())
    if (result == true)
        Print v1 is less than v2
    result = lexicographical_compare(v1.begin(), v1.end(), v2.begin(), v2.end())
    if (result == false)
        Print v1 is not less than v2
End

使用例

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
int main(void) {
    // v1とv2の初期化
    vector<string> v1 = {"One", "Two", "Three"};
    vector<string> v2 = {"one", "two", "three"};
    bool result;
    result = lexicographical_compare(v1.begin(), v1.end(), v2.begin(), v2.end());
    if (result == true)
        cout << "v1 is less than v2." << endl;
        v1[0] = "two";
        result = lexicographical_compare(v1.begin(), v1.end(), v2.begin(), v2.end());
    if (result == false)
        cout << "v1 is not less than v2." << endl;
    return 0;
}

このプログラムでは、まず文字列ベクトル v1 = {"One", "Two", "Three"} と v2 = {"one", "two", "three"} を比較します。大文字の 'O'(ASCIIコード 79)は小文字の 'o'(ASCIIコード 111)よりも小さいため、v1 は v2 より辞書順で小さいと判定され、最初のメッセージが出力されます。その後、v1[0] を "two" に書き換えて再比較すると、先頭要素 "two" が "one" より大きいため、v1 は v2 より小さくないと判定されます。

出力

v1 is less than v2.
v1 is not less than v2.
  1. C++のSTLでset_intersectionを実装し、2つの集合の積集合を求める方法

    2つの集合の積集合(インターセクション)とは、両方の集合に共通して含まれる要素だけを集めたものです。set_intersection関数によってコピーされる要素は、必ず最初の集合から取り出され、元の順序がそのまま維持されます。また、この関数を正しく動作させるためには、処理前に両方の集合がそれぞれソート済みである必要があります。 集合に対する代表的な操作には、以下のようなものがあります。 和集合(ユニオン) 積集合(インターセクション) 対称差(排他的論理和・XOR) 差集合(減算) アルゴリズム Begin   結果を格納するvector型変数vとイテレータstを宣言する。   st =

  2. 【C++】STLのset_differenceを使って2つの集合の差分を求める方法

    2つの集合の「差(差集合)」とは、1つ目の集合には存在するが、2つ目の集合には存在しない要素だけから構成される集合のことです。set_difference関数によってコピーされる要素は、必ず1つ目の集合から取り出され、元の順序が保たれます。また、この関数を正しく動作させるためには、両方の集合があらかじめソート(整列)されている必要があります。代表的な集合演算には以下のようなものがあります。和集合(Union)積集合(Intersection)対称差(Symmetric Difference / 排他的論理和)差集合(Difference / 減算)アルゴリズムBegin 集合用のvec