You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对std::deque<std::pair<std::string,std::string>>执行不区分大小写排序

C++ deque<pair<string,string>> 按首元素不区分大小写排序实现

核心实现思路

你只需要先实现一个大小写不敏感的字符串比较逻辑,再在sort的自定义比较lambda中调用该逻辑对比pair的第一个元素即可。

完整实现代码

首先引入必要的头文件:

#include <cctype>
#include <algorithm>
#include <deque>
#include <string>
#include <utility>

实现大小写不敏感的字符串比较函数:

// 大小写不敏感的字符串比较,返回true表示a应该排在b前面
bool caseInsensitiveStrCmp(const std::string& a, const std::string& b) {
    size_t minLen = std::min(a.size(), b.size());
    for (size_t i = 0; i < minLen; ++i) {
        // 转unsigned char避免char为有符号类型时传入负数导致未定义行为
        unsigned char ca = std::tolower(static_cast<unsigned char>(a[i]));
        unsigned char cb = std::tolower(static_cast<unsigned char>(b[i]));
        if (ca != cb) {
            return ca < cb;
        }
    }
    // 前面字符都相等时,短的字符串排在前面
    return a.size() < b.size();
}

调用sort时传入自定义比较lambda:

std::sort(mFiles.begin(), mFiles.end(), [](const std::pair<std::string, std::string>& a, const std::pair<std::string, std::string>& b) {
    // 仅对比pair的第一个元素,忽略大小写
    return caseInsensitiveStrCmp(a.first, b.first);
});

可选优化

如果你需要在第一个元素大小写不敏感相等时,继续按第二个元素排序,可以修改lambda逻辑:

std::sort(mFiles.begin(), mFiles.end(), [](const std::pair<std::string, std::string>& a, const std::pair<std::string, std::string>& b) {
    if (caseInsensitiveStrCmp(a.first, b.first)) return true;
    if (caseInsensitiveStrCmp(b.first, a.first)) return false;
    // 首元素相等时,按第二个元素排序,可按需选择是否忽略大小写
    return caseInsensitiveStrCmp(a.second, b.second);
    // 如果不需要忽略第二个元素的大小写,也可以直接写 return a.second < b.second;
});

注意事项

  • 上述实现仅适用于ASCII字符集场景,如果涉及中文、Unicode等非ASCII字符,需要使用对应字符集的大小写转换接口。
  • lambda参数使用const&可以避免不必要的对象拷贝,大幅提升排序性能。

内容的提问来源于stack exchange,提问作者volt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 14:45:09