Is there an efficient way to check which currency my user wants to convert?
Solution 1:
Choose one base currency. Express all other currencies in terms of this base currency. Then you can populate a map of conversion factors and use it:
#include <iostream>
#include <map>
int main()
{
std::map<std::string,int> conversions { {"dollars",100},{"pennies",1}};
// ^ 1 dollar = 100 pennies
std::cout << "amount: ";
double amount = 0;
std::cin >> amount;
std::cout << "from: ";
std::string from;
std::cin >> from;
std::cout << "to : ";
std::string to;
std::cin >> to;
auto ifrom = conversions.find(from);
auto ito = conversions.find(to);
if (ifrom == conversions.end() || ito == conversions.end()) return 0;
double result = amount * ifrom->second / ito->second;
std::cout << result;
}
For example:
amount: 100
from: dollars
to : pennies
10000
std::map<std::string,int>
is an associative container. It stores key (std::string
)-value (int
) pairs. It is sorted, though its just my bad habit of using std::map
when an unsorted std::unordered_map
would work as well. Its find
method can be used to look up an element for a given key. If the key is not found in the map the end iterator is returned. Hence, before dereferencing the returned iterator one needs to check for equality to end()
. It the returned iterator is not the end iterator one can use the iterators first
and second
to get the key and mappend value, respectively.