我有字符串std::string str(s);
,s 有类似的单词列表
s="one two three one one two..."
而且我希望每个单词的出现以及具有最大出现值的结尾单词。
我已经声明了发生类型:
typedef std::unordered_map<std::string> occurrences;
occurrences s1;
我想分配s
into的内容s1
,我该怎么做?
之后,这里是获取每个单词出现错误的代码:
for (std::unordered_map<std::string, int>::iterator it = s1.begin();
it != s1.end();
++it)
{
std::cout << "word :" << it->first << "occured " << it->second << " times \n";
}
谁能告诉我如何在这里出现每个单词“一”、“二”?
根据要求,我在这里添加原始代码:
#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 (std::unordered_map<std::string, int>::iterator it = s1.begin();it != s1.end();++it)
{
std::cout << "word :" << it->first << "occured " << it->second << " times \n";
}
return 0;
}
改进的代码:
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <unordered_map>
int main()
{
typedef std::unordered_map<std::string,int> occurrences;
occurrences s1;
// the string we're splitting.
std::string s = "one two three one one two";
int maxcount=0,temp=0;
std::vector<std::string> vestring;
// create an input string stream
std::istringstream iss(std::move(s));
// now simply extract strings until you reach end-of-file.
while (iss >> s)
{
temp=++s1[s];
if(temp>=maxcount)
{
maxcount=temp;
vestring.push_back(s);
}
}
for (occurrences::const_iterator it = s1.cbegin();it != s1.cend(); ++it)
std::cout << it->first << " : " << it->second << std::endl;;
return 0;
}