首页 > 解决方案 > 在 C++ 中查找字符串中的重复单词时输出错误

问题描述

你能告诉我为什么 1 出现在我的输出中,而我正在使用映射跟踪给定字符串中的单词和出现吗?

string x="Hello World Hello World";
//getline(cin,x);

map<string,int> store;
stringstream s(x);

do
{
    string y;
    s>>y;
    if(store.find(y)!=store.end())
    {
        auto it=store.find(y);
        it->second++;
    }
    else
        store.insert(pair<string,int>(y,1));
}while(s);
map<string, int>::iterator itr; //common for all maps

 for(itr=store.begin();itr!=store.end();++itr)
    cout<<itr->first<<" "<<itr->second<<endl; 

输出:

 1
Hello 2
World 2 

标签: c++maps

解决方案


我通过使用 y.length()>0 纠正了条件的其他部分,现在它似乎工作正常。


推荐阅读