Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I create a list like this in CPP? [closed]

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%
like image 537
user420 Avatar asked Feb 17 '26 07:02

user420


2 Answers

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).

like image 88
Yksisarvinen Avatar answered Feb 19 '26 21:02

Yksisarvinen


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;
}
like image 41
Arthur Grigoryan Avatar answered Feb 19 '26 19:02

Arthur Grigoryan