我下面的代码给了我字符串中出现次数最多的单词。我想从向量中获取三个最常出现的单词及其计数值。有什么帮助吗?
我用过vector
和unordered_map
。在代码的最后一部分中,我从vector
.
int main(int argc,char *argv[])
{
typedef std::unordered_map<std::string,int> occurrences;
occurrences s1;
std::string input = argv[1];
std::istringstream iss(std::move(input));
std::vector<std::string> most;
int max_count = 0,second=0,third=0;
//Here I get max_count, 2nd highest and 3rd highest count value
while (iss >> input)
{
int tmp = ++s1[input];
if (tmp == max_count)
{
most.push_back(input);
}
else if (tmp > max_count)
{
max_count = tmp;
most.clear();
most.push_back(input);
third = second;
second = max_count;
}
else if (tmp > second)
{
third = second;
second = tmp;
}
else if (tmp > third)
{
third = tmp;
}
}
//I have not used max_count, second, third below. I dont know how to access them for my purpose
//Print each word with it's occurenece. This works fine
for (occurrences::const_iterator it = s1.cbegin();it != s1.cend(); ++it)
std::cout << it->first << " : " << it->second << std::endl;;
//Prints word which occurs max time. **Here I want to print 1st highest,2nd highest,3rd highest occuring word with there occurrence. How to do?**
std::cout << std::endl << "Maximum Occurrences" << std::endl;
for (std::vector<std::string>::const_iterator it = most.cbegin(); it != most.cend(); ++it)
std::cout << *it << std::endl;
return 0;
}
有什么想法可以得到 3 个最常出现的单词吗?