I'm trying to create an alphabet cipher in C++. My approach for this problem was creating two unordered maps. 1 with the letters and their according int position in the alphabet, and one opposite table.
When I try to access this unordered map in my function, encrypt, I'm getting an error message:
the map is not declared in this scope.
I'm still new to C++. Initially I tried creating the map above main, but this doesn't seem to work either.
Any suggestions or hints on how to approach a situation like this?
#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;
}
These are the error messages I'm getting:
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)) ===|
With VKNs explanation I managed to solve the program as follows!
#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);
}
If anyone else has any tips for conventions or anything else always welcome!