I am trying to write a description of each of the actions in the code by commenting on things performed in the code.
Could you please help me understand what does "createdCode->second"
do and re-check if my made comments about the other parts are correct?
Here is the code:
#include <map>
#include <string>
#include <iostream>
int main() {
// Stores everything that is that specific std namespace and dumps it in the global namespace as characters in key-value pairs and declares them as strings.
std::map<char, std::string> natoAlphabet = {
{'A', "Alfa"}, {'B', "Bravo"}, {'C', "Charlie"},
{'D', "Delta"}, {'E', "Echo"}, {'F', "Foxtrot"},
{'G', "Golf"}, {'H', "Hotel"}, {'I', "India"},
{'J', "Juliet"}, {'K', "Kilo"}, {'L', "Lima"},
{'M', "Mike"}, {'N', "November"}, {'O', "Oscar"},
{'P', "Papa"}, {'Q', "Quebec"}, {'R', "Romeo"},
{'S', "Sierra"}, {'T', "Tango"}, {'U', "Uniform"},
{'V', "Victor"}, {'W', "Whiskey"}, {'X', "Xray"},
{'Y', "Yankee"}, {'Z', "Zulu"}, {'0', "Zero"}
};
// Declare the input & Open Terminal
char ch;
std::cin >> ch;
// Created a variable that has a complicated type and find the element from declared characters in the array as strings.
auto createdCode = natoAlphabet.find(ch);
// Execute the If Statement that checks if inputed values will match the information in the natoAlphabet array.
// If it does not match - output "Not recognized:".
if (createdCode == natoAlphabet.end())
std::cout << "Not recognized." << std::endl;
else
std::cout << createdCode->second << std::endl;
return 0;
}
CodePudding user response:
find
returns an iterator. When you are confused by types, I suggest to stay away from auto
for a moment. auto
is not to ignore what the actual type is (at least to my understanding).
std::map<char,std::string>::iterator iter = natoAlphabet.find(ch);
If find
cannot find the element then it returns natoAlphabet.end()
, the end iterator that refers to an element one past the last element. So actually it does not refer to an element in the map. It is just used to denote the end of the map. find
uses it to indicate that the element was not found:
if (iter == natoAlphabet.end())
std::cout << "Not recognized." << std::endl;
When the element is found, then the iterator refers to a std::pair<const char,std::string>
, because thats the type of elements in a std::map<char,std::string>
. You get a reference to the key via iter->first
and a reference to the mapped value via iter->second
. Hence,
else
std::cout << iter->second << std::endl;
Prints the std::string
for the key ch
when there is an element with that key in the map.
For more details I refer you to https://en.cppreference.com/w/cpp/container/map
PS: Unless you need the map to be sorted you shoud rather use std::unorderd_map
.