unordered_map не объявлено в области видимости - PullRequest
0 голосов
/ 26 февраля 2020

Я пытаюсь создать алфавитный шифр в C ++. Мой подход к этой проблеме заключался в создании двух неупорядоченных карт. 1 с буквами и их соответствующей позицией int в алфавите и одной противоположной таблицей.

Когда я пытаюсь получить доступ к этой неупорядоченной карте в моей функции шифрования, я получаю сообщение об ошибке:

карта не объявлена ​​в этой области.

Я все еще новичок в C ++. Первоначально я пытался создать карту выше основной, но, похоже, это тоже не сработало.

Какие-либо предложения или советы о том, как подходить к такой ситуации?

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

string enCrypt (string str, int x){ //encrypts the input letter with the offset variable (encryption key) x
    int pos = cipherMap.at(str);
    string encrypted;
    if (pos + x < 25){
        encrypted = alphaMap.at(pos + x);
        return encrypted;
    }else{
        pos = 25 - pos;
        encrypted = alphaMap.at(x - pos);
        return encrypted;
    }
}

int main()
{
    vector<string> alphabet(26);
    iota(alphabet.begin(), alphabet.end(), 'A');

    unordered_map<string, int> cipherMap; //map containing the alphabet and the corresponding position of the letter in the alphabet
    for (int i = 0; i < 26; i++){
        cipherMap.insert( { alphabet[i], i });
    }

    unordered_map<int, string> alphaMap; //opposite of earlier mentioned map
    for (int i = 0; i < 26; i++){
        alphaMap.insert( { i , alphabet[i] });
    }

    cout << enCrypt("A", 3); //trying to encrypt letter A, output should be D


    return 0;
}

Это Я получаю сообщения об ошибках:

D:\Reddit Projects\Encryption Cipher\main.cpp||In function 'std::__cxx11::string enCrypt(std::__cxx11::string, int)':|
D:\Reddit Projects\Encryption Cipher\main.cpp|9|error: 'cipherMap' was not declared in this scope|
D:\Reddit Projects\Encryption Cipher\main.cpp|12|error: 'alphaMap' was not declared in this scope|
D:\Reddit Projects\Encryption Cipher\main.cpp|16|error: 'alphaMap' was not declared in this scope|
||=== Build failed: 3 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

С объяснениями VKN мне удалось решить программу следующим образом!

#include <unordered_map>
#include <string>
#include <vector>
#include <numeric>
using namespace std;

struct Cipher{
    Cipher (vector<string> alphabet){
        for (int i = 0; i < 26; i++){
            cipherMap.insert( { alphabet[i], i });
        }
        for (int i = 0; i < 26; i++){
            alphaMap.insert( { i , alphabet[i] });
        }
    }
    string encrypt (string str, int x){
        int pos = cipherMap.at(str);
        string encrypted;
        if (pos + x < 25){
            encrypted = alphaMap.at(pos + x);
            return encrypted;
        }else{
            pos = 25 - pos;
            encrypted = alphaMap.at(x - pos);
            return encrypted;

        }
    }
private:
    unordered_map<string, int> cipherMap;
    unordered_map<int, string> alphaMap;
};

int main()
{

        vector<string> alphabet(26);
        iota(alphabet.begin(), alphabet.end(), 'A');

        Cipher cipher{alphabet};
        cout << cipher.encrypt("A", 3);
}

Если у кого-то есть какие-либо советы по соглашениям или что-либо еще, всегда приветствую !

1 Ответ

0 голосов
/ 26 февраля 2020

Вот ваша main область действия:

vector алфавит (26);

unordered_map cipherMap;

unordered_map alphaMap;

Когда вы вызываете string enCrypt(string str, int x), функция может видеть в своей точке входа:

string str;

int x;

Вы не передали ему ни одного из unordered_map, поэтому он не знает, о чем вы говорите. Чтение функции сверху вниз:

int pos

Существует переменная с именем pos, которая содержит целое число.

= cipherMap .at (str);

Что присваивается тому, о чем я не знаю (я знаю только о string str, int x и int pos на данном этапе).

Существует несколько способов решения этой проблемы: от передачи ссылок на unordered_map до функции и до того, как класс будет обрабатывать все это для вас (что, вероятно, является лучшим выбором). Примерно так:

struct Cipher {
    Cipher(string alphabet)
    { //...initializes the unordered_maps
    }

    string encrypt(string str, int x)
    { //......
    }
private:
    unordered_map<string, int> cipherMap;
    unordered_map<int, string> alphaMap;
};

int main()
{
    string alphabet;
    //Initialize your alphabet and do whatever you must
    Cipher cipher{alphabet};
    string encrypted = cipher.encrypt(/* Some other string */);
}

Таким образом, функция encrypt может видеть переменные-члены unordered_map класса Cipher, так как она также является членом Cipher.

...