bse*_*sem 5 c++ sorting string case-insensitive
基本上,我必须使用选择排序来对string[]. 我已经完成了这部分,但这是我遇到的困难。
然而,排序应该是不区分大小写的,这样“天线”就会出现在“木星”之前。ASCII 从大写到小写排序,所以没有办法只交换排序字符串的顺序吗?或者有更简单的解决方案吗?
void stringSort(string array[], int size) {
    int startScan, minIndex;
    string minValue;
    for(startScan = 0 ; startScan < (size - 1); startScan++) {
        minIndex = startScan;
        minValue = array[startScan];
        for (int index = startScan + 1; index < size; index++) {
            if (array[index] < minValue) {
                minValue = array[index];
                minIndex = index;
            }
        }
        array[minIndex] = array[startScan];
        array[startScan] = minValue;
    }
}
C++ 为您提供了sortwhich 需要一个比较函数。在您的情况下,vector<string>您将比较两个字符串。true如果第一个参数较小,则比较函数应返回。
对于我们的比较函数,我们希望找到应用string后 s之间的第一个不匹配字符tolower。为此,我们可以使用mismatchwhich 在两个字符之间使用比较器true,只要它们相等就返回:
const auto result = mismatch(lhs.cbegin(), lhs.cend(), rhs.cbegin(), rhs.cend(), [](const unsigned char lhs, const unsigned char rhs){return tolower(lhs) == tolower(rhs);});
要确定 是否lhs小于rhs美联储,mismatch我们需要测试 3 件事:
string不等长的sstring lhs短char的lhs小于第一个不匹配char的rhs该评估可以通过以下方式进行:
result.second != rhs.cend() && (result.first == lhs.cend() || tolower(*result.first) < tolower(*result.second));
最终,我们希望将其封装在一个 lambda 表达式中并将其插入sort作为我们的比较器:
sort(foo.begin(), foo.end(), [](const unsigned char lhs, const unsigned char rhs){
    const auto result = mismatch(lhs.cbegin(), lhs.cend(), rhs.cbegin(), rhs.cend(), [](const unsigned char lhs, const unsigned char rhs){return tolower(lhs) == tolower(rhs);});
    return result.second != rhs.cend() && (result.first == lhs.cend() || tolower(*result.first) < tolower(*result.second));
});
这将正确排序vector<string> foo。你可以在这里看到一个活生生的例子:http : //ideone.com/BVgyD2
编辑:
刚刚看到你的问题更新。您也可以使用sortwith string array[]。你只需要这样称呼它:sort(array, std::next(array, size),...
| 归档时间: | 
 | 
| 查看次数: | 8837 次 | 
| 最近记录: |