应在“.”之前使用主表达式ordered_map()中的令牌

expected primary-expression before ‘.’ token in ordered_map()

本文关键字:map 令牌 ordered 表达式 应在      更新时间:2023-10-16

我想插入段落或文章内容并处理每个单词。下面我试图得到每个字符串,然后得到它的出现次数。最后我想要最大出现次数的单词。我是c++新手。现在我已经静态地插入了两个字符串。这给出了错误CCD_ 1。代码如下:`

#include <string>
#include <iostream>
#include <unordered_map>
int main()
{
    typedef std::unordered_map<std::string,int> occurrences;
    occurrences s1;
    s1.insert(std::pair<std::string,int>("Hello",1));
    s1.insert(std::pair<std::string,int>("Hellos",2));
    //for ( auto it = occurrences.begin(); it != occurrences.end(); ++it )  this also gives same + additional " error: unable to deduce ‘auto’ from ‘<expression error>’" error
    for (std::unordered_map<std::string, int>::iterator it = occurrences.begin();//Error is here
                                                    it != occurrences.end(); ////Error is here
                                                    ++it)
    {
        std::cout << "words :" << it->first << "occured" << it->second <<  "times";
    }
    return 0;
}

错误在哪里?

occurrences是一种类型,而不是对象。您想要使用对象s1

版本1:

for (auto it = s1.begin(); it != s1.end(); ++it)

版本2:

for (std::unordered_map<std::string, int>::iterator it = s1.begin(); it != s1.end(); ++it)

版本3:

for (auto pair : s1)

您需要使用s1.begin()s1.end(),而不是occurrences.begin()occurrences.end(),因为occurrences是一种类型,而s1是该类型的变量。