如何在C++中对地图中的值进行排序
问题描述:
我想根据值对输出进行排序,但我不确定如何处理它。 这是我的电流输出:如何在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";
}
}
答
我们初学者应该互相帮助:)
在任何情况下,您需要第二个容器,因为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
我想知道谁是那么聪明谁投票了你的初学者有趣的问题。 –
你应该考虑使用std :: unordered_map –