patterncppMinor
Assigning atomic number based on atomic symbol
Viewed 0 times
numbersymbolbasedassigningatomic
Problem
I currently have the following code:
The code simply takes in a string
How can this be done more effectively?
unsigned int symToZ(const std::string & sym){
unsigned int atomicNum;
if(sym == "H"){atomicNum = 1;}
else if(sym == "He"){atomicNum = 2;}
else if(sym == "Li"){atomicNum = 3;}
else if(sym == "Be"){atomicNum = 4;}
else if(sym == "B"){atomicNum = 5;}
else if(sym == "C"){atomicNum = 6;}
else if(sym == "N"){atomicNum = 7;}
else if(sym == "O"){atomicNum = 8;}
else if(sym == "F"){atomicNum = 9;}
...
return atomicNum;
}The code simply takes in a string
sym (which is the atomic symbol, such as He, F, Au, and so on), and converts it to the respective atomic number. As you can see, it involves a lot of repeated code. For such simple code, I feel it is needlessly complex.How can this be done more effectively?
Solution
The most efficient way is to use
Above, you get the number out of a symbol in constant time which improves on going through a lot of
unordered_map since C++11:int main(int argc, const char * argv[]) {
std::unordered_map symbol_to_number = {
{"H", 1},
{"He", 2},
{"Li", 3},
// And so on..
};
// Usage:
std::cout << symbol_to_number["H"] << std::endl;
return 0;
}Above, you get the number out of a symbol in constant time which improves on going through a lot of
if statements.Code Snippets
int main(int argc, const char * argv[]) {
std::unordered_map<std::string, unsigned int> symbol_to_number = {
{"H", 1},
{"He", 2},
{"Li", 3},
// And so on..
};
// Usage:
std::cout << symbol_to_number["H"] << std::endl;
return 0;
}Context
StackExchange Code Review Q#149499, answer score: 6
Revisions (0)
No revisions yet.