字符串映射字符串输出对应关系(可拓展)

44 阅读1分钟

除了使用 switch 语句之外,可以考虑使用 map 来实现字符串到字符串的映射。map 是 C++ STL 中的关联容器,可以存储键值对,因此可以用来实现字符串到字符串的映射关系。

#include <iostream>
#include <map>
#include <string>
using namespace std;

string getMappedString(const string& input) {
    // 创建一个映射关系的 map
    map<string, string> stringMap = {
        {"Jan", "January"},
        {"Feb", "February"},
        {"Mar", "March"},
        // 添加更多映射关系
    };

    // 查找输入字符串对应的映射值
    auto it = stringMap.find(input);
    if (it != stringMap.end()) {
        return it->second;  // 返回找到的映射值
    } else {
        return "Not found"; // 如果没有找到对应映射,则返回"Not found"
    }
}

int main() {
    string input;
    cout << "Enter a string: ";
    cin >> input;

    string output = getMappedString(input);
    cout << "Mapped string: " << output << endl;

    return 0;
}