c++中使用映射对记事本中的字符进行排序

c++ using maps to sort a notepads characters

本文关键字:字符 排序 映射 c++ 记事本      更新时间:2023-10-16

我希望通过使用映射来查找文本文件中每个字符的数量来对文本文件进行排序。我想我已经很接近了。

void CharStatistic(string filename)
{
    ifstream infile;
    infile.open(filename);
    char x;
    int i;
    map <char, int> count;
    while (infile >> x)
    {
        count[x]++;
        for (auto it = count.begin(); it != count.end(); it++)
            cout << it->first << it->second << endl;
    }
}

这是我正在读取的文件中的实际内容。

Computer science is the scientific and practical approach to computation and its applications. It is the systematic study of the feasibility, structure, expression, and mechanization of the methodical procedures (or algorithms) that underlie the acquisition, representation, processing, storage, communication of, and access to information, whether such information is encoded as bits in a computer memory or transcribed in genes and protein structures in a biological cell. An alternate, more succinct definition of computer science is the study of automating algorithmic processes that scale. A computer scientist specializes in the theory of computation and the design of computational systems.
    Its subfields can be divided into a variety of theoretical and practical disciplines. Some fields, such as computational complexity theory (which explores the fundamental properties of computational and intractable problems), are highly abstract, while fields such as computer graphics emphasize real-world visual applications. Still other fields focus on the challenges in implementing computation. For example, programming language theory considers various approaches to the description of computation, while the study of computer programming itself investigates various aspects of the use of programming language and complex systems. Human-computer interaction considers the challenges in making computers and computations useful, usable, and universally accessible to humans.

如果可能的话,我还想弄清楚如何打印出出现最多的字符。和往常一样,非常感谢任何帮助!

在这种情况下我不会使用map。如果一个简单数组只有256个值,那么它只占用1kb(假设每个计数占用4个字节)。即使输入可能是稀疏的,所以该数组的一些元素没有使用,只有1k,您不太可能通过使用不同的结构获得任何东西。

完成计数后,转换为可以按计数排序的结构数组非常容易(或者,如果您确实只需要计数最大的结构,则只需对该结构进行线性扫描)。

修改代码

void CharStatistic(string filename) {
    ifstream infile(filename);
    if (!infile.is_open()) return;    // Check if file opened correctly
    char x;
    map<char, int> count;
    while (infile >> x) count[x]++;
    for (auto it : count)    // Pull this out of the while loop
        cout << it.first << " " << it.second << endl;
}

查找最大出现次数

int max = *max_element(count.begin(), count.end(), count.value_comp());
  • 不要在每次循环中都打印map的值。
  • 要按顺序打印最高频率,将您的映射内容转储到std::pair的'std::vector',并使用基于pair的第二个元素比较值的比较器对其进行排序。
  • 最后显示排序后的向量。