簡體   English   中英

如何將映射鍵更改為值並將值更改為鍵?

[英]How to change map keys into values and values into keys?

我編寫了一個加密和解密字符串的小程序。 我生成地圖和字符,我添加隨機值,所以我有一個密鑰來加密數據。 我在解密時遇到問題。 我想將映射鍵更改為值並將值更改為鍵並使用它來解密,但我不知道該怎么做。

這是我的密鑰生成器。 我將標志向前移動 13 位(用於測試)。 最終,偏移值將是隨機的。

std::map<char, char> generateKey(){

    std::map<char, char> map;
    char ascii = ' ', sign, newSign;
    int randomNumber = 13, overScale;

    for(int i = 0; i < 94; i++){
        if(ascii+i+randomNumber <= 126){
            sign = ascii+i;
            newSign = ascii+i+randomNumber;
            std::pair pair = std::pair(sign, newSign);
            map.insert(pair);
        } else{
            overScale = abs((ascii+i+randomNumber) - 126);
            sign = ascii+i;
            newSign = ascii+overScale-1;
            std::pair pair = std::pair(sign, newSign);
            map.insert(pair);
        }
    }
    return map;
}

您可以使用std::transform來填充新的std::map

#include <algorithm>
#include <iostream>
#include <iterator>
#include <map>

int main() {
    // your original map:
    std::map<char, char> ma {
        {'a','b'},
        {'c','d'},
    };

    // the target map
    std::map<char, char> mb;

    // transforming using a lambda that swaps key and value
    std::transform(ma.begin(), ma.end(), std::inserter(mb, mb.begin()),
        [](const auto& pair) -> decltype(mb)::value_type {
            return {pair.second, pair.first};
        }
    );

    // printing the result
    for(auto [key, value] : mb) {
        std::cout << key << ' ' << value << '\n';
    }
}

輸出:

b a
d c

創建加密映射時,您也可以創建解密映射,

此示例使用這些預先構建的數據結構加密和解密消息:

#include <stdio.h>
#include<map>
#include<string>
#include<iostream>
#include<random>

int main()
{
    std::map<char, char> encryptMap;
    std::map<char, char> decryptMap;
    char ascii = ' ', sign, newSign;
    int randomNumber = std::rand(), overScale;

    for(int i = 0; i < 94; i++){
        if(ascii+i+randomNumber <= 126){
            sign = ascii+i;
            newSign = ascii+i+randomNumber;
        } else{
            overScale = abs((ascii+i+randomNumber) - 126);
            sign = ascii+i;
            newSign = ascii+overScale-1;
        }
        encryptMap.insert(std::pair(sign, newSign));
        decryptMap.insert(std::pair(newSign, sign));
    }

    std::string message = "This is a text for ceaser cipher";
    std::string encryptedMessage;
    std::string decryptedMessage;
    for(auto const& c:message){
        encryptedMessage += encryptMap[c];
    }

    std::cout << encryptedMessage << std::endl;

    for(auto const& c:encryptedMessage){
        decryptedMessage += decryptMap[c];
    }

    std::cout << decryptedMessage;

    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM