In this HackerRank Maps-STL problem in c++ programming language, You are appointed as the assistant to a teacher in a school and she is correcting the answer sheets of the students. Each student can have multiple answer sheets. So the teacher has Q queries:
- X Y: Add the marks Y to the student whose name is X.
- X: Erase the marks of the students whose name is X.
- X: Print the marks of the students whose name is X. (If X didn’t get any marks print 0.)
HackerRank Maps-STL problem solution in c++ programming.
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <set> #include <map> #include <algorithm> using namespace std; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int q,type; cin>>q; string name; int marks; map<string,int> m; for(int i=0;i<q;i++) { cin>>type; switch(type) { case 1: cin>>name>>marks; if(m.find(name)==m.end()) m.insert(make_pair(name,marks)); else m[name]+=marks; break; case 2: cin>>name; m.erase(name); break; case 3: cin>>name; m.find(name)!=m.end()?cout<<m.find(name)->second<<endl:cout<<"0"<<endl; break; } } return 0; }
Second solution
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <set> #include <map> #include <algorithm> using namespace std; int main() { int n; cin >> n; map<string, int> m; while (n--) { int t; cin >> t; string s; cin >> s; if (t == 1) { int a; cin >> a; m[s] += a; } else if (t == 2) { m[s] = 0; } else { cout << m[s] << "n"; } } return 0; }