I have string std::string str(s);
and s has list of words like
s="one two three one one two..."
And I want occurrence of each word and at the end word with max occurrence value.
I have declared occurrence type :
typedef std::unordered_map<std::string> occurrences;
occurrences s1;
and I want to assign content of s
into s1
, How can I do it?
After that here is the code to get occurrence of each words which has some mistake:
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";
}
Can Any one tell me how can I get occurance of each word "one" , "two" here?
As per request I am adding original code here:
#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;
}
Improved code:
#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;
}