This is for my grade 11 cs class. I am creating a program that converts levels to percentages. This is a list I made for my python code that shows users the percentages when they enter a level (ex. 3+)but I was wondering if I could do something like this in C++.
grade= {}
grade['R-'] = '0%'
grade['R'] = '30%'
grade['R+'] = '40%'
grade['1-'] = '50%'
grade['1'] = '53%'
grade['1+'] = '57%'
grade['2-'] = '60%'
grade['2'] = '63%'
grade['2+'] = '67%'
grade['3-'] = '70%'
grade['3'] = '73%'
grade['3+'] = '77%'
grade['4-'] = '80%'
grade['4'] = '87%'
grade['4+'] = '95%
The most similar type to Python's dict is std::unordered_map (the order of elements is implementation-defined).
Note that Python 3.7 is guaranteed to preserve insertion order for dict, but no standard utility in C++ provides such functionality (unless you are willing to use std::vector<std::pair<...>>).
std::map guarantees that keys are sorted in some order (default is operator <, which for std::string means lexicographical order, like a real world dictionary).
You can use it like this:
#include <unordered_map>
#include <string>
int main()
{
std::unordered_map<std::string, std::string> grade;
grade["R-"] = "0%";
grade["R"] = "30%";
grade["R+"] = "40%";
grade["1-"] = "50%";
grade["1"] = "53%";
grade["1+"] = "57%";
grade["2-"] = "60%";
grade["2"] = "63%";
grade["2+"] = "67%";
grade["3-"] = "70%";
grade["3"] = "73%";
grade["3+"] = "77%";
grade["4-"] = "80%";
grade["4"] = "87%";
grade["4+"] = "95%";
}
Notice the double quotes - C++ sees the difference between single quotes (used for single char) and double quotes (used for a string).
Of course you can like this:
#include <iostream>
#include <string>
#include <map>
using namespace std;
void main()
{
map<string, string> grade;
grade["R-"] = "0%";
grade["R"] = "30%";
grade["R+"] = "40%";
grade["1-"] = "50%";
grade["1"] = "53%";
grade["1+"] = "57%";
grade["2-"] = "60%";
grade["2"] = "63%";
grade["2+"] = "67%";
grade["3-"] = "70%";
grade["3"] = "73%";
grade["3+"] = "77%";
grade["4-"] = "80%";
grade["4"] = "87%";
grade["4+"] = "95%";
cout << '{';
for (auto item : grade) {
cout << '\'' << item.first << ": '" << item.second << "', ";
}
cout << '}' << endl;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With