Devlog/Coding Practice

[C++][STL] Maps-STL

FATKITTY 2021. 11. 21. 15:45
반응형

https://www.hackerrank.com/challenges/cpp-maps/problem

 

 

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <set>
#include <map>
#include <algorithm>
using namespace std;


int main() {
    int q = 0, t = 0, mark = 0;
    string name;
    map<string, int> m;
    // Gives the iterator to the element name if it is found otherwise returns m.end()
    map<string, int>::iterator itr;

    cin >> q;
    for (int i = 0; i < q; i++) {
        cin >> t;
        switch (t) {
        case 1:
            cin >> name >> mark;
            itr = m.find(name);
            if (itr == m.end()) m.insert(make_pair(name, mark));
            else itr->second += mark;
            break;
        case 2:
            cin >> name;
            m.erase(name);
            break;
        case 3:
            cin >> name;
            itr = m.find(name);
            if (itr != m.end()) cout << itr->second << endl;
            else cout << 0 << endl;
            break;
        }
    }

    return 0;
}

 

Reference

http://www.cplusplus.com/reference/map/map/

 

반응형