我想制作一個字母頻率表,就像這個
。所以,我有一個變數str,它包含一些文本,我有map<char, int> m,它包含每個字母出現的次數。
所以我有這樣的東西:
vector<char> get_rank(const string& str)
{
map<char, int> m;
for (char i = 'a'/span>; i <= 'z'; i )
m[i] = 0;
for (char ch : str)
m[ch] 。
for (auto& it : m)
v.push_back(it.first)。
return v。
但是map是按鍵排序,而不是按值排序。是否有辦法 "多載 "map的比較器,使每個元素按值排序?如果答案是否定的,我怎樣才能實作同樣的想法,但有同樣的雅致。因為我的每一個想法都顯得有些沉悶和粗糙。
uj5u.com熱心網友回復:
不可能根據地圖的映射值來對其進行排序。地圖元素的順序是由地圖根據其比較器來管理的,它只考慮鍵。
然而,當鍵是連續的且范圍有限時,你不需要地圖來計算頻率。
代替地圖,使用一個std::vector<letter_and_count>與
struct letter_and_count{
char letter。
int count = 0;
};
用letter初始化向量的元素為a,直到z,然后當你在字串中遇到字母i時增加v[ i - 'a'>。然后使用std::sort來根據count成員對向量進行排序。
PS: 注意下面的評論。從a到z的字母不一定相鄰。然而(eerorika的想法)你可以使用一個簡單的查找表:
std::string alphabet{"abcdefghijklmnopqrstuvwxyz"/span>};
然后首先找到該字母表中的字母,并使用其在字母表中的索引進行計數。
uj5u.com熱心網友回復:
有沒有一種方法可以 "多載 "map的比較器來按值排序每個元素?
沒有。
如果答案是否定的,那么我怎樣才能實作同樣的想法,但又有同樣的優雅。
取決于使用情況。這個例子的一個優雅解決方案是對矢量進行排序。
uj5u.com熱心網友回復:
不要試圖用一個顯然不是為此設計的STL容器來做一些事情(對地圖進行排序),也許可以使用一個不同的容器。
你總是可以使用 這些都可以被排序。 我更喜歡 uj5u.com熱心網友回復: 我認為使用專門的容器的方法是可以的。 對于計數應該使用 這將以一種通用的方式作業。也可以使用最大堆來找到使用頻率最高的元素。 或者,在下面的例子中,我們可以找到一個最常用的元素。
或者,在下面的例子中,我們可以得到x個最重要的元素。而這只需要幾行代碼。下面的代碼將計算幾乎所有的東西,并根據價值進行排序:
上面的代碼是針對C 17的 而下面是一個例子,可以找到任何容器中最頻繁的元素。 但這是一個C 20的解決方案:
標籤: 上一篇:從Python中運行C 函式
std::pair<char, int>/code>作為std::vector的型別。
std::vector<std::pair<char,int>>只是因為我更習慣于使用向量,但這取決于你。
std::map或者std::unordered_map。之后,它可以被復制到一個std::vector中,并按照你的意愿進行排序。#include <iostream>
#include <utility>
#include <unordered_map>/span>
#include <algorithm>
#include <vector>
#include <iterator>
#include <type_traits>
// type trait的輔助工具 我們要識別一個可迭代的容器----------------------------------------------------
template <typename Container>
auto isIterableHelper(int) ->。decltype (
std::begin(std::declval<Container&>()) != std::end(std::declval<Container&>(), / begin/end and operator !=
std::declval<decltype(std::begin(std::declval<Container&>())&>(), //operator
void(*std::begin(std::declval<Container&>()), //operator*
void(), //處理潛在的運算子,。
std::true_type{})。
template <typename T>
std::false_type isIterableHelper(...)。
// The type trait -----------------------------------------------------------------------------------------------------
template <typename Container>
using is_iterable = decltype(isIterableHelper<Container>(0) )。
//有些別名是為了以后方便閱讀--------------------------------------------------------------------------。
template <typename Container>
using ValueType = std::decay_t<decltype(*std: :begin(std::declval<集裝箱&())>。
template <typename Container>
using Pair = std::pair<ValueType<Container>, size_t> 。
template <typename Container>
using Counter = std::unordered_map<ValueType<Container>, size_t> 。
// Function to get the k most frequent elements used in any Container ------------------------------------------------.
template <class Container>
auto topKFrequent(const Container& data, size_t k) {
if constexpr (is_iterable< Container> ::value) {
//計算所有資料的出現次數{
Counter<Container> counter{}。
for (const auto& d : data) counter[d] 。
///用于存盤最上面的k。
std::vector<Pair<Container>> top(k)。
//獲取頂部k。
std::partial_sort_copy(counter.begin(), counter. end(), top.begin(), top.end() 。
[](const std::pair<int, size_t >& P1, const std: :pair<int, size_t>& p2) { return p1. second > p2.second; })。)
return top;
}
else[/span
return data;
}
int main() {
std:: vector testVector{ 1,2,2,3, 3, 3,4,4,4, 5,5,5,6, 6,6,6,7 };
for (const auto& p : topKFrequent(testVector, 2)) std::cout << "值。" << p.first << " Count: " << p.second << '
'。
std::cout << '
'。
double cStyleArray[] = { 1.1, 2.2, 2。 2, 3.3, 3.3, 3.3 };
for (const auto& p : topKFrequent(cStyleArray, 2)) std::cout << "值。" << p.first << " Count: " << p.second << '
'。
std::cout << '
'。
std::string s{ "abbcccddddeeeeeffffggggg" }。
for (const auto& p : topKFrequent(s, 2) std::cout << "值。" << p.first << " Count: " << p.second << '
'。
std::cout << '
'。
double value = 12.34;
std::cout << topKFrequent(value, 2) << "
"。
return 0;
#include <iostream>
#include < utility>
#include <unordered_map>/span>
#include <queue>
#include <vector>
#include <iterator>
#include <type_traits>
#include <string>
//有些別名是為了以后方便閱讀--------------------------------------------------------------------------。
template <typename Container>
using ValueType = std::ranges::range_value_t< Container>。
template <typename Container>
using Pair = std::pair<ValueType<Container>, size_t> 。
template <typename Container>
using Counter = std::unordered_map<ValueType<Container>, size_t> 。
template <typename Container>
using UnderlyingContainer = std::vector<Pair<Container> >。
//Predicate Functor 謂詞向量。
template <class Container> struct LessForSecondOfPair{
bool operator ()(const Pair< Container>& p1, const Pair<Container>& p2) { return p1. second <p2.second;}
};
template <typename Container>
using MaxHeap = std::priority_queue<Pair<Container>, UnderlyingContainer<Container>, LessForSecondOfPair< Container>>。
// Calculate max element ---------------------------------------------------------------------------------------------
template <class Container>
auto topFrequent(const Container& data) {
if constexpr (std::range< Container>) {
//計算所有出現的資料
Counter<Container> counter{}。
for (const auto& d : data) counter[d] 。
//建立一個Max-Heap。
MaxHeap<Container> maxHeap(counter.begin(), counter.end())。
//回傳最頻繁的數字。
return maxHeap.top().first;
}
else[/span
return data。
}
// Test
int main() {
std:: vector testVector{ 1,2,2,3, 3, 3,4,4,4, 5,5,5,6, 6,6,6,7 };
std::cout << "最頻繁是。" << topFrequent(testVector) < < "
"。
double cStyleArray[] = { 1.1, 2.2, 2。 2, 3.3, 3.3, 3.3 };
std::cout << "最頻繁是。" << topFrequent(cStyleArray) < < "
"。
std::string s{ "abbcccddddeeeeeffffggggg" }。
std::cout << "最頻繁是。" << topFrequent(s) << "
"。
double value = 12.34;
std::cout << "最頻繁是。" << topFrequent(value) < < "
"。
return 0;
