使用地图来计数字符串输入

Using maps to count strings input

本文关键字:数字 字符串 输入 地图      更新时间:2023-10-16

我正在尝试使用映射计数重复单词,如果用户输入一旦输出为"确定"字符串,则输出将是字符串和重复时间的数字

旁边的字符串

我知道代码看起来很愚蠢,这是我第一次使用地图,我不熟悉该语法

任何帮助将不胜感激

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";