lexicographical_compare(beg,end,sbeg,send)和lexicographical_compare(beg,end,sbeg,send)的特点
1:返回值:布尔类型
2:迭代器类型:输入迭代器
3:无op版本,默认比较方式operator<,以字典比较方式比较区间[beg,end)和[sbeg,send)
4:有op版本,op为比较方式,op(elem1,selem)
字典比较
1:如果首元素不相等,它们的比较结果为序列的比较结果
2:如果首元素相等,比较它们的下一元素,它们的比较结果为序列的比较结果
3:如果元素都相等,比较两个序列的长度,序列长的大,所以如果如果第一序列元素较少返回值为true
4:如果序列相等,元素相等,返回false
#include<iostream>
#include<vector>
#include<functional>
using namespace std;
int main()
{
//无op版本
//false
vector<int>c1 = { 1,2,3,4,5 };
vector<int>c2 = { 1,2,3,4,5};
cout << lexicographical_compare(c1.begin(),c1.end(),c2.begin(),c2.end());
//true
vector<int>c1 = { 1,2,3,4,5 };
vector<int>c2 = { 2,2,3,4,5};
cout << lexicographical_compare(c1.begin(),c1.end(),c2.begin(),c2.end());
//true
vector<int>c1 = { 1,2,3,4,5 };
vector<int>c2 = { 1,3,3,4,5};
cout << lexicographical_compare(c1.begin(),c1.end(),c2.begin(),c2.end());
//true
vector<int>c1 = { 1,2,3,4,5 };
vector<int>c2 = { 1,2,3,4,5,1};
cout << lexicographical_compare(c1.begin(),c1.end(),c2.begin(),c2.end());
}
#include<iostream>
#include<vector>
#include<functional>
using namespace std;
int main()
{
//有op版本
//false
vector<int>c1 = { 1,2,3,4,5};
vector<int>c2 = { 1,2,3,4,5 };
cout << lexicographical_compare(c1.begin(), c1.end(), c2.begin(), c2.end(),greater<int>());
//true
vector<int>c1 = { 2,2,3,4,5};
vector<int>c2 = { 1,2,3,4,5 };
cout << lexicographical_compare(c1.begin(), c1.end(), c2.begin(), c2.end(),greater<int>());
//true
vector<int>c1 = { 1,3,3,4,5};
vector<int>c2 = { 1,2,3,4,5 };
cout << lexicographical_compare(c1.begin(), c1.end(), c2.begin(), c2.end(),greater<int>());
}
对于算法测试的疑惑:经过代码测试,发现当前端序列元素相等时,第一序列元素个数大于第二序列元素个数时返回值始终为false,不管op为less<>,还是greater<>,当第一序列元素个数小于第二序列元素个数时返回值始终为true,经过查阅和翻看源代码,发现当第一序列和第二序列前端元素相等时,算法返回值为_First1 == _Last1 && _First2 != _Last2,所以当比较完短序列后,算法的返回结果与想象中的,当前端元素相同时,序列长大于序列短的结果并不一致
#include<iostream>
#include<vector>
#include<functional>
using namespace std;
int main()
{
//结果均为1,并非想象中的 1 0
vector<int>c1 = { 1,2,3,4};
vector<int>c2 = { 1,2,3,4,5};
cout << lexicographical_compare(c1.begin(), c1.end(), c2.begin(), c2.end(),less<int>())<<endl;
cout << lexicographical_compare(c1.begin(), c1.end(), c2.begin(), c2.end(), greater<int>());
//结果均为0 0 并非想象中的 0 1
vector<int>c1 = { 1,2,3,4,5};
vector<int>c2 = { 1,2,3,4};
cout << lexicographical_compare(c1.begin(), c1.end(), c2.begin(), c2.end(),less<int>())<<endl;
cout << lexicographical_compare(c1.begin(), c1.end(), c2.begin(), c2.end(), greater<int>());
}
也有可能是作者水平过低,对序列长短不同时测试结果理解有误区,若有朋友知道原因,欢迎指正