Я пытаюсь создать алфавитный шифр в 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);
}
Если у кого-то есть какие-либо советы по соглашениям или что-либо еще, всегда приветствую !