1

我想插入段落或文章内容并处理每个单词。下面我试图获取每个字符串,然后得到它的出现。最后,我想要出现次数最多的单词。我是 C++ 新手。现在我已经静态插入了两个字符串。这给出了错误expected primary-expression before ‘.’ token。代码如下:`

#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 ‘&lt;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;
}

错误在哪里?

4

2 回答 2

1

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

于 2013-08-23T05:16:45.550 回答
1

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)
于 2013-08-23T05:17:21.527 回答