Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรม C++ ใช้งาน lexicographical_compare ใน STL

ฟังก์ชัน std::lexicographical_compare() ใน C++ ทดสอบว่าช่วงหนึ่งน้อยกว่าอีกช่วงหนึ่งตามลำดับเลขโซกไหม การเปรียบเทียบแบบเลขโซก (lexicographical) คือการเปรียบเทียบที่ใช้จัดเรียงคำในพจนานุกรม

การประกาศ

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

อัลกอริทึม

เริ่มต้น
  result = lexicographical_compare(v1.begin(), v1.end(), v2.begin(), v2.end())
  ถ้า (result == true)
    พิมพ์ v1 น้อยกว่า v2
  result = lexicographical_compare(v1.begin(), v1.end(), v2.begin(), v2.end())
  ถ้า (result == false)
    พิมพ์ v1 ไม่น้อยกว่า v2
สิ้นสุด

ตัวอย่างโค้ด

#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 is less than v2.
v1 is not less than v2.