我想在 c++ 的算法库中使用函数 lexicographical_compare 。
但就 using 语句而言,我不知道该写什么。例如
using std::lexicographical_compare ??
我如何才能在未来为自己解决这个问题?
谢谢
我想在 c++ 的算法库中使用函数 lexicographical_compare 。
但就 using 语句而言,我不知道该写什么。例如
using std::lexicographical_compare ??
我如何才能在未来为自己解决这个问题?
谢谢
做就是了
using std::lexicographical_compare;
然后(从SGI STL Doc复制)
int main()
{
int A1[] = {3, 1, 4, 1, 5, 9, 3};
int A2[] = {3, 1, 4, 2, 8, 5, 7};
int A3[] = {1, 2, 3, 4};
int A4[] = {1, 2, 3, 4, 5};
const int N1 = sizeof(A1) / sizeof(int);
const int N2 = sizeof(A2) / sizeof(int);
const int N3 = sizeof(A3) / sizeof(int);
const int N4 = sizeof(A4) / sizeof(int);
bool C12 = lexicographical_compare(A1, A1 + N1, A2, A2 + N2);
bool C34 = lexicographical_compare(A3, A3 + N3, A4, A4 + N4);
cout << "A1[] < A2[]: " << (C12 ? "true" : "false") << endl;
cout << "A3[] < A4[]: " << (C34 ? "true" : "false") << endl;
}
或者
// no using statement
int main()
{
//... same as above
bool C12 = std::lexicographical_compare(A1, A1 + N1, A2, A2 + N2);
bool C34 = std::lexicographical_compare(A3, A3 + N3, A4, A4 + N4);
//... same as above
}
要在未来了解自己,请从头到尾阅读 C++ 书籍(例如 Stroustrup 的“The C++ Programming Language”)。
用法示例,来自https://www.geeksforgeeks.org/lexicographical_compare-in-cpp/
// helper function to convert all into lower case:
bool comp (char s1, char s2) {
return tolower(s1)<tolower(s2);
}
void test_lexicographical_compare(){
// initializing char arrays
char one[] = "geeksforgeeks";
char two[] = "gfg";
// using lexicographical_compare for checking
// is "one" is less than "two"
if( lexicographical_compare(one, one+13, two, two+3)) {
cout << "geeksforgeeks is lexicographically less than gfg"<<endl;
}
else {
cout << "geeksforgeeks is not lexicographically less than gfg"<<endl;
}
// now two = "Gfg";
strncpy(two, "Gfg", 3);
// using lexicographical_compare for checking
// is "one" is less than "two"
// returns true this time as all converted into lowercase
if( lexicographical_compare(one, one+13, two, two+3, comp)){
cout << "geeksforgeeks is lexicographically less ";
cout << "than Gfg( case-insensitive )"<<endl;
}
else{
cout << "geeksforgeeks is not lexicographically less ";
cout<< "than Gfg( case-insensitive )"<<endl;
}
}
输出:
geeksforgeeks is lexicographically less than gfg
geeksforgeeks is lexicographically less than Gfg( case-insensitive )