利用set实现密钥的去重,利用unordered_map<char,char>实现密钥和字符之间的映射。

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

int main() {   
    string s1, s2;
    getline(cin, s1, '\n');
    getline(cin, s2, '\n');
    // 获得key
    set<char> s_key;    // 用于去重
    vector<char> v_key;
    for (int i = 0; i < s1.size(); i++) {
        if (s_key.find(s1[i]) != s_key.end()) { continue; }
        else {
            s_key.insert(s1[i]);
            v_key.push_back(s1[i]);
        }
    }
    // 扩展key
    for (int i = 0; i < 26; i++) {
        char ch = 'a' + i;
        if (s_key.find(ch) != s_key.end()) { continue; }
        else { v_key.push_back(ch); }
    }
    // 建立映射
    unordered_map<char,char> u_map;
    int k = 0;
    for (vector<char>::iterator iter = v_key.begin(); iter != v_key.end(); iter++) {
        auto key_val = *iter;
        char ch = 'a' + k;
        u_map[ch] = key_val;
        k++;
    }
    // 进行加密
    for (int i = 0; i < s2.size(); i++) {
        if (s2[i] >= 'A' && s2[i] <= 'Z') {
            // 大写字符
            char temp = s2[i] + 32;   // 转换为小写
            char temp_key = u_map[temp];
            temp_key = temp_key - 32;   // 小写转换为大写
            s2[i] = temp_key;
        } else if (s2[i] >= 'a' && s2[i] <= 'z') {
            // 小写字符
            char temp_key = u_map[s2[i]];
            s2[i] = temp_key;
        } else if (s2[i] = ' ') continue; 
    }
    cout << s2 << endl;
    return 0;
}