Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Chương trình C++ triển khai lexicographical_compare trong STL

Hàm std::algorithm::lexicographical_compare() trong C++ kiểm tra xem một phạm vi có nhỏ hơn phạm vi khác theo thứ tự từ điển hay không. So sánh từ điển là loại so sánh thường dùng để sắp xếp từ theo thứ tự bảng chữ cái trong từ điển.

Khai báo

template <class InputIterator1, class InputIterator2>

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

Thuật toán

Bắt đầu
  result = lexicographical_compare(v1.begin(), v1.end(), v2.begin(), v2.end())
  if (result == true)
    In v1 nhỏ hơn v2
  result = lexicographical_compare(v1.begin(), v1.end(), v2.begin(), v2.end())
  if (result == false)
    In v1 không nhỏ hơn v2
Kết thúc

Ví dụ

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;

int main(void) {
  // khởi tạo v1 và 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;
}

Kết quả

v1 is less than v2.
v1 is not less than v2.