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 次浏览

开启您的 职业生涯

完成课程,取得认证

开始学习
广告