简体   繁体   中英

First most repeated word based on insertion order

I have a bunch of words inserted in a string in order. Now, i'd like to find the most repeated word. If there is a tie, use the earlier word.

Code: https://ideone.com/S5yOBk

#include <iostream>
#include <map>
#include <sstream>
using namespace std;

int main()
{
    string line = "paper block book chair";
    map<string, int> frequencyMap;

        istringstream stream(line);
        string word;

        while (stream >> word)
        {
            ++frequencyMap[word];
        }

        string maxRep; int c = 0;
        for (auto& t : frequencyMap) {
            if (t.second > c) {
                maxRep = t.first;
                c = t.second;
            }
        }

    cout << "First Most repeated word is: " << maxRep << endl;
}

Expected output is "paper" in this case, but i keep getting "block".

You can't decide which element will appear first in map based on the order on which you insert them in the map. You should consider using another field to know which will keep the insertion order.

There is an easy solution like this:-

#include <iostream>
#include <map>
#include <sstream>
using namespace std;

int main()
{
    string line = "paper block book chair";
    map<string, pair<int,int>> frequencyMap;

        istringstream stream(line);
        string word;
        int i = 0;
        while (stream >> word)
        {
            if(frequencyMap.count(word)==0)
             frequencyMap[word]=pair<int,int>(i++,1);
            else
                frequencyMap[word].second++;
        }

    string maxRep; int c = 0,ord=10000000;// max elements inserted+1
    for (auto& t : frequencyMap) {
        if (t.second.second > c ||(t.second.second==c && t.second.first < ord)) {
            maxRep = t.first;
            ord = t.second.first;
            c = t.second.second;
        }
    }

    cout << "First Most repeated word is: " << maxRep << endl;
}

Output: 
paper

std::map is base on a sort of BST, every first class it stores should have “opetator <“ to make BST ordered. std::string is ordered lexicographicaly.

You can write a new class contains the string and the time it insert in, compare every two elements by their insert-time,so the std::map is ordered by inserting time.

upd

I rethink this problem and find that you just need to is record the times every string occurs and maintain the maximum times. If some string occurs time is greater than the maximum times we recorded previously, we update the maximum times and change the answer into this string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM