利用unordered_map和stable_sort()函数实现自定义的稳定排序

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <unordered_map>
using namespace std;

// 用于记录排序顺序
unordered_map<char, int> orders;
// 比较函数
bool cmp(char lhs, char rhs) {
    return orders[lhs] < orders[rhs];
}
// 判断是不是字母
bool isLetter(char c) {
    return c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z';
}
int main() {
    // 初始化map
    for (char c = 'a'; c <= 'z'; ++c) {
        orders[c] = c - 'a';
    }
    for (char c = 'A'; c <= 'Z'; ++c) {
        orders[c] = c - 'A';
    }
    string str;
    while (getline(cin, str)) {
        // vector只存放字母
        vector<char> chars;
        for (int i = 0; i < str.length(); ++i) {
            if (isLetter(str[i])) {
                chars.push_back(str[i]);
            }
        }
        // 对vector进行稳定排序
        stable_sort(chars.begin(), chars.end(), cmp);
        // 将str内的字母替换为vector中的字母
        for (int i = 0; i < str.length(); ++i) {
            if (isLetter(str[i])) {
                str[i] = chars.front();
                chars.erase(chars.begin());
            }
        }
        // 输出字符串
        cout << str << endl;
    }
}