【发布时间】:2016-05-06 04:19:25
【问题描述】:
我编写了下面的代码,它使用了Map。该程序查找string 键在Map 中出现的次数。如果它只出现一次,那么该 string 键的 int 的值应该是 1,依此类推。该程序运行并产生所需的输出 - 但我觉得这纯粹是运气,因为我没有在任何地方初始化 Map。我只是在做myMap[str]++ - 这绝不保证最初的值是0。那么,我如何初始化映射,以便任何string 键的值都是0,在遇到它之前我执行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;
}
示例输入:
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
示例输出:
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
详细问题描述可见here。
谢谢!
【问题讨论】:
标签: c++ stl initialization