2017-06-09 43 views
-2

我想根據值對輸出進行排序,但我不確定如何處理它。 這是我的電流輸出:如何在C++中對地圖中的值進行排序

E:2 
H:1 
I:3 
L:2 
N:3 
O:2 
S:2 
T:1 
Y:1 

這是我多麼希望我的輸出:

I: 3 
N: 3 
E: 2 
L: 2 
O: 2 
S: 2 
H: 1 
T: 1 
Y: 1 

我的代碼:

#include<iostream> 
using std::cin; 
using std::cout; 
using std::endl; 
#include<string> 
using std::string; 
#include<map> 
using std::map; 
#include<algorithm> 
using std::sort; 

int main() 
{ 
    string input; 
    int line = 0; 
    map<char, int> letters; 
    while (getline(cin, input)) 
    { 
     line += 1; 
     for (int i = 0; i < input.length(); i++) 
     { 
      if (isalpha(input[i])) 
      { 
       if (letters.count(toupper(input[i])) == 0) 
       { 
        letters[toupper(input[i])] = 1; 
       } 
       else 
       { 
        letters[toupper(input[i])] += 1; 
       } 
      } 
     } 
    } 

    cout << "Processed " << line << " line(s)." << endl; 
    cout << "Letters and their frequency:" << endl; 
    for (auto it = letters.cbegin(); it != letters.cend(); ++it) 
    { 

     cout << it->first << ":" << it->second << "\n"; 

    } 
} 
+0

我想知道誰是那麼聰明誰投票了你的初學者有趣的問題。 –

+0

你應該考慮使用std :: unordered_map –

回答

1

我們初學者應該互相幫助:)

在任何情況下,您需要第二個容器,因爲std::map是已經按鍵排序。

一般的方法是將地圖複製到其他容器中,並在輸出之前對新容器進行排序。

對於您的任務,您可以使用std::set作爲第二個容器。

給你。

#include <iostream> 
#include <map> 
#include <set> 
#include <utility> 

int main() 
{ 
    std::map<char, size_t> m = 
    { 
     { 'E', 2 }, { 'H', 1 }, { 'I', 3 }, { 'L', 2 }, 
     { 'N', 3 }, { 'O', 2 }, { 'S', 2 }, { 'T', 1 }, 
     { 'Y', 1 } 
    }; 

    for (const auto &p : m) 
    { 
     std::cout << "{ " << p.first << ", " << p.second << " }\n"; 
    } 
    std::cout << std::endl; 

    auto cmp = [](const auto &p1, const auto &p2) 
    { 
     return p2.second < p1.second || !(p1.second < p2.second) && p1.first < p2.first; 
    }; 

    std::set < std::pair<char, size_t>, decltype(cmp)> s(m.begin(), m.end(), cmp); 

    for (const auto &p : s) 
    { 
     std::cout << "{ " << p.first << ", " << p.second << " }\n"; 
    } 
    std::cout << std::endl; 
} 

程序輸出是

{ E, 2 } 
{ H, 1 } 
{ I, 3 } 
{ L, 2 } 
{ N, 3 } 
{ O, 2 } 
{ S, 2 } 
{ T, 1 } 
{ Y, 1 } 

{ I, 3 } 
{ N, 3 } 
{ E, 2 } 
{ L, 2 } 
{ O, 2 } 
{ S, 2 } 
{ H, 1 } 
{ T, 1 } 
{ Y, 1 } 

另外要注意,在你的程序,而不是這個if-else語句的

if (letters.count(toupper(input[i])) == 0) 
{ 
    letters[toupper(input[i])] = 1; 
} 
else 
{ 
    letters[toupper(input[i])] += 1; 
} 

,你可以只寫

++letters[toupper(input[i])]; 
+0

對你好Vlad :) – Monza

相關問題