I have written the below code which uses a Map
. This program finds the number of times the string
key appears in the Map
. If it appears only once, then the value of int
for that string
key should be 1, and so on. This program runs and produces the required output - but I feel that it is pure luck, because I am not initializing the Map anywhere. I am just doing myMap[str]++
- this in no way guarantees that initially the value was 0
. So, how do I initialize the map so that the value for any string
key is 0
, before it is encountered and I do a myMap[str]++
?
#include<cstdio>
#include<string>
#include<iostream>
#include<map>
int main()
{
int t;
long int n;
std::string str;
std::map< std::string, int > myMap;
scanf("%d", &t);
while(t--)
{
scanf("%ld", &n);
std::cin.ignore();
while(n--)
{
getline(std::cin, str);
myMap[str]++;
}
for(std::map< std::string, int >::iterator it=myMap.begin(); it!=myMap.end(); it++)
printf("%s %d\n", it->first.c_str(), it->second);
printf("\n");
myMap.erase(myMap.begin(), myMap.end());
}
return 0;
}
Sample input:
2
6
03 10103538 2222 1233 6160 0142
03 10103538 2222 1233 6160 0141
30 10103538 2222 1233 6160 0141
30 10103538 2222 1233 6160 0142
30 10103538 2222 1233 6160 0141
30 10103538 2222 1233 6160 0142
5
30 10103538 2222 1233 6160 0144
30 10103538 2222 1233 6160 0142
30 10103538 2222 1233 6160 0145
30 10103538 2222 1233 6160 0146
30 10103538 2222 1233 6160 0143
Sample output:
03 10103538 2222 1233 6160 0141 1
03 10103538 2222 1233 6160 0142 1
30 10103538 2222 1233 6160 0141 2
30 10103538 2222 1233 6160 0142 2
30 10103538 2222 1233 6160 0142 1
30 10103538 2222 1233 6160 0143 1
30 10103538 2222 1233 6160 0144 1
30 10103538 2222 1233 6160 0145 1
30 10103538 2222 1233 6160 0146 1
Detailed problem description can be found here.
Thanks!