C++ 程式在 STL 中實現 LexicoGraphical_Compare


C++ 函式 std::algorithm::lexicographical_compare() 會測試一個範圍是否詞法上小於另一個,或與另一個是否相等。詞法上的比較通常用於對字典中的單詞按字母順序排序。

宣告

template <class InputIterator1, class InputIterator2>

bool lexicographical_compare(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2);

演算法

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) {
   //initialization of v1 and 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 is less than v2.
v1 is not less than v2.

更新於: 30-7-2019

82 次瀏覽

開啟您的 職業生涯

完成課程,取得認證

開始學習
廣告
© . All rights reserved.