哪种方法更适合霍夫曼编码 我想读取字符及其频率
which method is more suitable for huffman encoding i want to read chars with their frequency
两个从字符串中读取字符的循环
void ReadCharWithFreq(string str){
int n = str.size();
int count = 0;
// loops to read all char from string and frequency
for(int i = 0;i<n;i++){
for(int x =0;x<n;x++ ){
if(str[i]==str[x]){
count++;
}
}
//enqueue char with frequency
enqueue(str[i],count);
count=0;
}
} //end of function
相同的功能,不同的方法使用堆数组 freq[] 和模因集我不明白模因集(数组,整数,整数)的功能
void ReadCharWithFreq(string str){
int n = str.size();
int SIZE = 40;
int spf=0;
memset(freq, 0, sizeof(freq));
for (int i = 0; i < n; i++){
freq[str[i] - 'a']++;
}
for (int i = 0; i < n; i++) {
if (freq[str[i] - 'a'] != 0) {
cout << str[i] <<" "<< freq[str[i] - 'a'] << " - >";
enqueue(str[i], freq[str[i] - 'a']);
freq[str[i] - 'a'] = 0;
}
}
} //end of function
以上哪一种算法更准确高效我想从字符串中读取所有字符并计算它们的出现次数/频率
我会使用一个空间足以容纳您可能遇到的所有字符计数的std::array
:
#include <array>
#include <limits>
constexpr size_t ArrSize = std::numeric_limits<unsigned char>::max()+1;
std::array<unsigned char, ArrSize> ReadCharWithFreq(const std::string& str){
std::array<unsigned char, ArrSize> freq{};
for(unsigned char ch : str)
freq[ch]++;
return freq;
}
用法示例:
#include <iostream>
#include <iomanip>
#include <vector>
int main(int argc, char* argv[]) {
std::vector<std::string> args(argv+1, argv+argc);
for(const auto& str : args) {
auto result = ReadCharWithFreq(str);
for(size_t i=0; i<ArrSize; ++i) {
if(result[i]) {
std::cout << std::setw(3) << i << " " << static_cast<char>(i) << " " << static_cast<int>(result[i]) << "n";
// enqueue here?
}
}
}
}
相关文章:
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- 从矢量C++读取字符时出现问题
- 从格式化输入操作中获取读取字符数
- 使用 cin.get 读取字符数组
- 按下回车键时,如何使数组停止读取字符
- C++:读取字符是不正确的
- 如何从输入文件中读取字符并将其存储到向量中?
- 线程函数无法从堆上分配的缓冲区中读取字符
- 使用 cin.get() 读取字符
- C++:使用 fgets() 读取字符输入时出错
- C++ 从文件中读取字符,计算每个字符并进行排序
- C ++ ifstream 无法读取字符串,并且在读取字符时出错
- 逐字读取字符数组,无需字符串函数
- 是否有任何方法可以在用户输入文本时读取字符
- 从字符串中读取字符时出错
- 如何按字符从文件到2D数组读取字符
- 重载>>运算符和读取字符
- 从堆栈中读取字符后,如何修复不正确的文件输出
- 如何从文件中读取“”字符
- 读取字符 * 始终具有相同的地址