使用地图来计数字符串输入
Using maps to count strings input
我正在尝试使用映射计数重复单词,如果用户输入一旦输出为"确定"字符串,则输出将是字符串和重复时间的数字
旁边的字符串我知道代码看起来很愚蠢,这是我第一次使用地图,我不熟悉该语法
任何帮助将不胜感激
int main()
{
int t, i = 0;
string s;
map<string, int> m;
cin >> t;
while (t--) {
cin >> s;
m[s] = i++;
if (i == 0)
cout << "OK";
else
cout << m[s] << m.second << endl;
}
}
cin >> s;
m[s]++;
if (m[s] == 1)
cout << "OKn";
else
cout << "this is the " << m[s] << "th occurence of " << s << "n";
请注意,即使s
尚未在地图中,您也可以使用m[s]
,因为操作员[]
将自动添加并初始化其第二个。
编辑:要避免两次地图中的搜索(请参阅@slava的评论),我们可以以这种方式做得更好(更快):
cin >> s;
i = ++m[s];
if (i == 1)
cout << "OKn";
else
cout << "this is the " << i << "th occurence of " << s << "n";
相关文章:
- 生成随机长度的数字字符串
- 如何在c ++中将大数字字符串转换为整数?
- 将非数字字符串存储为二进制整数
- Flex 词法分析器规则,对包含连字符和斜杠的字母数字字符串具有积极的前瞻断言
- 如何在C++中将数字字符串拆分为数组
- 总结数字字符串输入的最佳方法
- 如何将输入的数字字符串转换为 int 数组
- 如何获得两个数字字符串的总和-C
- 使用 C++ 替换 txt 文件中的文本数字字符串
- 如何有效地将数字字符串值分配给整数
- String Stream in C++ 解析单词和数字字符串
- c++将大型数字字符串映射到数字字符串范围
- 获取用数字字符串表示的树中的所有直接父级/子级
- 如何从 char 数组中提取数字字符串成员
- 比较两个字母数字字符串
- 有没有一种方法可以设置浮点变量=某个数字*字符串中的变量
- 使用矢量对字母数字字符串进行排序
- 正在分析未知类型的数字字符串
- 如何在c++中从一个科学数字字符串中修剪后面的零
- 无法将字符串数组中的数字字符串转换为浮点值