p5266C++代码
查看原帖
p5266C++代码
1713921
Georgefly楼主2025/7/1 16:18

前言

很多人不会这题
所以帮你们写下代码:

正片开始

#include <bits/stdc++.h>
using namespace std;

int main() {
    unordered_map< string, int> students;
    int n;
    cin >> n;
    cin.ignore();

    for (int i = 0; i < n; ++i) {
        int op;
        string name;
        int score;

        cin >> op;
        if (op == 1) {
            cin >> name >> score;
            students[name] = score;
            cout << "OK" <<  endl;
        } else if (op == 2) {
            cin >> name;
            auto it = students.find(name);
            if (it != students.end()) {
                cout << it->second <<  endl;
            } else {
                cout << "Not found" <<  endl;
            }
        } else if (op == 3) {
            cin >> name;
            auto it = students.find(name);
            if (it != students.end()) {
                students.erase(it);
                cout << "Deleted successfully" <<  ::endl;
            } else {
                cout << "Not found" <<  ::endl;
            }
        } else if (op == 4) {
            cout << students.size() <<  ::endl;
        }
    }
    return 0;
}

~这代码一点也不多(bushi)~

所以简化一下:

#include <iostream>
#include <unordered_map>
#include <string>

using namespace std;

int main() {
    unordered_map<string, int> students;
    int n;
    cin >> n;
    cin.ignore();

    for (int i = 0; i < n; ++i) {
        int op;
        string name;
        int score;

        cin >> op;
        switch (op) {
            case 1:
                cin >> name >> score;
                students[name] = score;
                cout << "OK" << endl;
                break;
            case 2:
                cin >> name;
                if (students.contains(name)) {
                    cout << students[name] << endl;
                } else {
                    cout << "Not found" << endl;
                }
                break;
            case 3:
                cin >> name;
                if (students.erase(name) > 0) {
                    cout << "Deleted successfully" << endl;
                } else {
                    cout << "Not found" << endl;
                }
                break;
            case 4:
                cout << students.size() << endl;
                break;
            default:
                cout << "Invalid operation" << endl;
        }
    }
    return 0;
}

显然,这已经很少了(反正我不能再简化了
(点个关注吧)

2025/7/1 16:18
加载中...