lexicographical_compare

lexicographical_compare,計算機程式語言函式,見於C++語言。

lexicographical_compare:
C++ STL 泛型算法函式:用於按字典序比較兩個序列。
函式申明:
//重載1,如果[first1, last1)按字典序列小於[first2, last2),返回true,否則返回false。
template <class InputIterator1, class InputIterator2 >
BOOL
lexicographical_compare(
InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2 );
//重載2,功能同重載1,增加了比較函式comp,即大小關係由comp函式確定。
template < class InputIterator1, class InputIterator2,
class Compare >
bool
lexicographical_compare(
InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2,
Compare comp );
示例代碼:
#include <algorithm>
#include <iostream>
#include <iterator>
using namespace std;
void Output(const int * a,const int & a_size,const int * b,const int & b_size)
{
cout<<"a[]=";
copy(a,a+a_size,ostream_iterator<int>(cout," "));
cout<<endl;
cout<<"b[]=";
copy(b,b+b_size,ostream_iterator<int>(cout," "));
cout<<endl;
}
typedef bool (* CMP)(const int &,const int &);
int Compare(const int * a,const int & a_size,const int * b,const int & b_size,CMP cmp) //按照cmp方式進行比較
{
bool ASmallerThanB,BSmallerThanA;
ASmallerThanB=lexicographical_compare(a,a+a_size,b,b+b_size,cmp); //按照cmp方式進行比較
BSmallerThanA=lexicographical_compare(b,b+b_size,a,a+a_size,cmp);
if(! ASmallerThanB && ! BSmallerThanA) //a[] 和 b[] 相等
return 0;
else if(ASmallerThanB) //a[] < b[]
return -1;
else
return 1;
}
int Compare(const int * a,const int & a_size,const int * b,const int & b_size) //默認比較方式
{
bool ASmallerThanB,BSmallerThanA;
ASmallerThanB=lexicographical_compare(a,a+a_size,b,b+b_size); //默認比較方式
BSmallerThanA=lexicographical_compare(b,b+b_size,a,a+a_size);
if(! ASmallerThanB && ! BSmallerThanA) //a[] 和 b[] 相等
return 0;
else if(ASmallerThanB) //a[] < b[]
return -1;
else
return 1;
}
bool greater(const int & a,const int & b) //自定義越大的字典序越小
{
return a>b;
}
int main()
{
int a[]={1,2,3,4,5,6};
int b[]={1,2,3,4,5,6};
Output(a,6,b,6);
cout<<"Compare(a,6,b,6)="<<Compare(a,6,b,6)<<endl;
cout<<"Compare(a,6,b,6,greater)="<<Compare(a,6,b,6,greater)<<endl;
rotate(a+2,a+4,a+6);
Output(a,6,b,6);
cout<<"Compare(a,6,b,6)="<<Compare(a,6,b,6)<<endl;
cout<<"Compare(a,6,b,6,greater)="<<Compare(a,6,b,6,greater)<<endl;
return 0;
}
return a>b;
}
int main()
{
int a[]={1,2,3,4,5,6};
int b[]={1,2,3,4,5,6};
Output(a,6,b,6);
cout<<"Compare(a,6,b,6)="<<Compare(a,6,b,6)<<endl;
cout<<"Compare(a,6,b,6,greater)="<<Compare(a,6,b,6,greater)<<endl;
rotate(a+2,a+4,a+6);
Output(a,6,b,6);
cout<<"Compare(a,6,b,6)="<<Compare(a,6,b,6)<<endl;
cout<<"Compare(a,6,b,6,greater)="<<Compare(a,6,b,6,greater)<<endl;
return 0;
}

相關詞條

相關搜尋

熱門詞條

聯絡我們