有几种可能性,取决于您是否想要这种行为:
如果您想行为一次:只需使用您自己的(自定义)算法:
bool isSpace(char i) { return i == '-' or i == ' '; }
int compare(std::string const& left, std::string const& right) {
typedef std::string::const_iterator ConstIterator;
typedef std::pair<ConstIterator, ConstIterator> Result;
size_t const size = std::min(left.size(), right.size());
Result const r = std::mismatch(left.begin(),
left.begin() + size,
right.begin(),
[](char a, char b) {
return a == b or (isSpace(a) and isSpace(b));
});
if (r.first == left.begin() + size) { // equal up til the end, shorter wins
return left.size() < right.size() ? -1 :
(left.size() == right.size() ? 0 : 1);
}
// not equal until the end
return *r.first < *r.second ? -1 : 1;
}
如果此行为需要在类本身中进行编码,您需要使用basic_string 并提供自定义特征类。
traits 类提供了一个 static int compare ( const char_type* s1, const char_type* s2, size_t n); 函数,供 std::string::compare 在后台使用。
例如:
struct MyTraits: char_traits<char> // too lazy to reimplement everything
{
static int compare(const char_type* s1, const char_type* s2, size_t n);
// definition can be trivially derived from the above version
};
typedef std::basic_string<char, MyTraits> MyString;
当然,MyString 与其他std::string 完全不兼容。
坦率地说,如果可以的话,只需“规范化”您的字符串并决定是使用 '-' 还是 ' '。它会让你的生活更轻松。