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

如何在C++中为Atbash密码加解密程序实现缓存功能

Atbash加解密缓存功能实现方案

实现思路

  • 缓存封装:定义独立的AtbashCache类,内部用unordered_map<string, string>存储「原始字符串-加解密结果」键值对,避免重复计算,所有缓存操作都封装在类内,耦合度更低。
  • 标准流打印:友元重载operator<<,遍历缓存内所有键值对格式化输出到流,直接支持cout << 缓存对象的打印需求。
  • 文件持久化:实现saveToFile和loadFromFile两个成员方法,用制表符分隔每对记录的键和值,避免普通空格的分隔冲突,支持本地存储和读取。
  • 逻辑优化:修复原代码中非字母字符的判断逻辑错误,同时替换原遍历字母表的加解密逻辑为ASCII直接计算,执行效率更高。

完整实现代码

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

// 缓存类
class AtbashCache {
private:
    unordered_map<string, string> data;
public:
    size_t size() const {
        return data.size();
    }

    bool has(const string& key) const {
        return data.find(key) != data.end();
    }

    string get(const string& key) const {
        return data.at(key);
    }

    void put(const string& key, const string& value) {
        data[key] = value;
    }

    void clear() {
        data.clear();
    }

    // 重载流输出运算符
    friend ostream& operator<<(ostream& os, const AtbashCache& cache) {
        os << "===== 缓存记录(共" << cache.size() << "条) =====" << endl;
        int index = 1;
        for (const auto& item : cache.data) {
            os << index << ". 原始内容:" << item.first << " | 处理结果:" << item.second << endl;
            index++;
        }
        return os;
    }

    // 保存缓存到文件
    bool saveToFile(const string& filePath) const {
        ofstream outFile(filePath);
        if (!outFile.is_open()) {
            return false;
        }
        for (const auto& item : data) {
            // 替换内容中的制表符为空格,避免分隔冲突
            string key = item.first;
            string value = item.second;
            replace(key.begin(), key.end(), '\t', ' ');
            replace(value.begin(), value.end(), '\t', ' ');
            outFile << key << "\t" << value << endl;
        }
        outFile.close();
        return true;
    }

    // 从文件加载缓存
    bool loadFromFile(const string& filePath) {
        ifstream inFile(filePath);
        if (!inFile.is_open()) {
            return false;
        }
        data.clear();
        string line;
        while (getline(inFile, line)) {
            size_t splitPos = line.find('\t');
            if (splitPos == string::npos) {
                continue;
            }
            string key = line.substr(0, splitPos);
            string value = line.substr(splitPos + 1);
            data[key] = value;
        }
        inFile.close();
        return true;
    }
};

// Atbash加解密逻辑(加密解密为同一操作)
string Atbash_cipher(const string& message) {
    string cipher;
    cipher.reserve(message.size());
    for (char c : message) {
        if (c >= 'A' && c <= 'Z') {
            cipher += 'Z' - (c - 'A');
        } else if (c >= 'a' && c <= 'z') {
            cipher += 'z' - (c - 'a');
        } else {
            // 非字母字符直接保留
            cipher += c;
        }
    }
    return cipher;
}

void menu() {
    int choice;
    string message, filePath;
    AtbashCache cache;
    do {
        cout << endl << "===== 功能菜单 =====" << endl
             << "1. 加密消息" << endl
             << "2. 解密消息" << endl
             << "3. 打印所有缓存记录" << endl
             << "4. 保存缓存到本地文件" << endl
             << "5. 从本地文件加载缓存" << endl
             << "0. 退出" << endl
             << "请输入你的选择:";
        cin >> choice;
        cin.ignore(); // 清除输入缓冲区的换行符
        switch (choice) {
            case 1:
            case 2:
                cout << "请输入要" << (choice == 1 ? "加密" : "解密") << "的内容:";
                getline(cin, message);
                string result;
                if (cache.has(message)) {
                    result = cache.get(message);
                    cout << "命中缓存,结果为:" << result << endl;
                } else {
                    result = Atbash_cipher(message);
                    cache.put(message, result);
                    cout << "计算结果为:" << result << endl;
                }
                break;
            case 3:
                cout << cache << endl;
                break;
            case 4:
                cout << "请输入保存文件的路径:";
                getline(cin, filePath);
                if (cache.saveToFile(filePath)) {
                    cout << "缓存保存成功" << endl;
                } else {
                    cout << "缓存保存失败,请检查路径是否合法" << endl;
                }
                break;
            case 5:
                cout << "请输入加载文件的路径:";
                getline(cin, filePath);
                if (cache.loadFromFile(filePath)) {
                    cout << "缓存加载成功,共加载" << cache.size() << "条记录" << endl;
                } else {
                    cout << "缓存加载失败,请检查路径是否合法" << endl;
                }
                break;
            case 0:
                cout << "退出程序" << endl;
                break;
            default:
                cout << "输入不合法,请重新输入" << endl;
        }
    } while (choice != 0);
}

int main() {
    menu();
    return 0;
}

功能说明

  • 加解密操作会优先查询缓存,已有记录直接返回结果,无需重复计算
  • 选择打印缓存即可直接输出所有已存储的记录
  • 保存/加载功能支持将缓存持久化到本地文件,程序重启后可恢复历史记录

内容的提问来源于stack exchange,提问作者Ростислав Русев

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 08:54:06