Initialize my std :: map

I wrote the code below that uses Map . This program finds the number of times the string key is displayed in Map . If it appears only once, then the int value for this key string must be 1 and so on. This program launches and produces the required output - but I feel that it is just luck, because I do not initialize the card anywhere. I just do myMap[str]++ - this in no way guarantees that the value was initially 0 . So, how to initialize the map so that the value for any string key is 0 before it meets, and I will do 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; } 

Input Example:

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

Output Example:

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

A detailed description of the problem can be found here .

Thanks!

+5
source share
2 answers

You said:

this in no way guarantees that the value was initially 0

This is not true. If the element corresponding to the key is not on the map, this value is initialized using the operator[] function.

From http://en.cppreference.com/w/cpp/container/map/operator_at :

If insertion is performed, the displayed value is initialized with a value (built by default for class types, zero-initialized otherwise) and a link to it is returned.

In other words,

  myMap[str]++; 

is the correct and correct code.

+5
source

You can check if the key already exists with std::map::find() . If it exists, you increment the element pointed to by the iterator returned from find. In addition, you write myMap[str] = 0 .

  while(n--) { getline(std::cin, str); std::map< std::string, int >::iterator it = myMap.find(str); if( myMap.end() != it ) (*it).second++; else myMap[str] = 1; } 

However, your code is fine, since int is initialized in your code. It is simply not visible ( std::pair<string,int> is created by default).

0
source

All Articles