ฟังก์ชัน C++ std::algorithm::lexicographical_compare() จะทดสอบว่าช่วงหนึ่งมีค่าน้อยกว่าช่วงอื่นหรือไม่ การเปรียบเทียบศัพท์เป็นประเภทของการเปรียบเทียบโดยทั่วไปที่ใช้ในการจัดเรียงคำตามตัวอักษรในพจนานุกรม
ประกาศ
เทมเพลต <คลาส InputIterator1, คลาส 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.