我有串std::string str(s);
和S有一個像 s="one two three one one two..."
創建使用unordered_map得到詞次數
單詞的列表,而且我想在與最大的出現值端字每個字的和發生哈希函數。
我宣佈發生類型:
typedef std::unordered_map<std::string> occurrences;
occurrences s1;
,我想的s
內容分配到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;
}
您是否熟悉['std :: istringstream <>'](http://en.cppreference.com/w/cpp/io/basic_istringstream)類?你也可以找到['std :: istream_iterator <>'](http://en.cppreference.com/w/cpp/iterator/istream_iterator)有幫助。 – WhozCraig
@WhozCraig:我不知道。我讀過它,但沒有得到如何使用它在我的情況! – user123