Nic*_*ace 1 c++ algorithm data-structures
词典比较意味着
如果我们有字符串"cat""apple""dog""算法",在它们按字典顺序相互比较后,它们按照字典顺序排列如下
算法,苹果,猫,狗
我编写了以下比较器,用于按字典顺序对这些字符串进行排序.
inline bool leq(int a1, int a2, int b1, int b2)
{
return (a1 < b1 || a1 == b1 && a2 <= b2);
}
inline bool leq(int a1, int a2, int a3, int b1, int b2, int b3)
{
return(a1 < b1 || a1 == b1 && leq(a2, a3, b2, b3));
}
Run Code Online (Sandbox Code Playgroud)
现在我试图引入另外两个不属于字母集"%"和"&"的符号,这样在排序字符串(字母集)时,"%"应该被视为小于所有字母,并且应该考虑"&"比所有字母都要大
如果我有
"apple%"和"apple&"那么apple%应该被认为小于apple&
有人可以建议我如何用c ++写这个.谢谢
<algorithm>标题中有一个算法可以执行字典比较,恰当地命名lexicographical_compare.有什么好处是你可以提供自己的比较功能,它可以考虑你的特殊字符:
#include <algorithm>
#include <string>
bool SpecialCharCompare(char lhs, char rhs) {
// I'll leave the implementation of the '%', '&' special casing to you.
// One way to do it would be to check if lhs/rhs are '%' or '&', in
// which case, you can assign them to some other char value such as
// ('a' - 1) or ('z' + 1).
}
int main(int argc, char** argv) {
std::string s1("apple%");
std::string s2("apple&");
bool result = std::lexicographical_compare(
s1.begin(), s1.end(),
s2.begin(), s2.end(),
SpecialCharCompare
);
if (result) {
// s1 is less than s2
} else {
// s1 is NOT less than s2
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)