簡體   English   中英

根據插入順序排列的第一個重復次數最高的單詞

[英]First most repeated word based on insertion order

我有一堆單詞按順序插入字符串中。 現在,我想找到最重復的單詞。 如果有平局,請使用前面的單詞。

代碼: 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;
}

在這種情況下,預期輸出為“紙張”,但我一直處於“阻塞”狀態。

您無法根據將元素插入地圖的順序來決定哪個元素將首先出現在地圖中。 您應該考慮使用另一個字段來知道哪個將保留插入順序。

有一個簡單的解決方案是這樣的:

#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是基於某種BST的,它存儲的每個第一類都應具有“ opetator <”以使BST排序。 std :: string是按字典順序排序的。

您可以編寫一個包含字符串及其插入時間的新類,並通過插入時間比較每兩個元素,以便按插入時間對std :: map進行排序。

UPD

我重新考慮了這個問題,發現您只需要記錄每個字符串出現的時間並保持最大時間即可。 如果某個字符串出現的時間大於我們之前記錄的最大時間,我們將更新最大時間並將答案更改為該字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM