gpt4 book ai didi

c++ - 如何在排序时保持数组的位置相同?

转载 作者:行者123 更新时间:2023-11-28 04:54:05 24 4
gpt4 key购买 nike

我正在编写一个凯撒密码解码程序,该程序按降序对消息中字母的出现频率进行排序。我的问题是当我打印出结果时,数组中频率的位置不再与我设置的字母匹配。我该如何解决?我还有其他代码可以从正在解码的消息中删除标点符号和大写字母、空格和小写字母以外的所有字符。

我已将代码精简到只剩下被质疑的部分。

#include<iostream>
#include<string>
#include<fstream>

using namespace std;

void sortArray(int*, int);

int main()
{

string fileContent = "a coded message which is several hundreds of characters long is being passed into the program";

int count[26];

// This code is skipping over spaces and other characters

for(int f = 0; f < fileContent.length(); f++)
{
if(fileContent[f] == 32)
{
continue;
}

if(fileContent[f] >= 48 && fileContent[f] <= 57)
{
continue;
}

count[(fileContent[f]-'a')%26]++;
}

// Here is where my issue begins. In sortArray, the position of the characters are being changed.

cout << "Letter frequency: Most common to least common" << endl;

sortArray(count, 26);

for(int p = 0; p < 26; p++)
{
cout << char(p + 97) << ": " << count[p] << endl;
}

return 0;
}



void sortArray(int* srcArray, int numElements)
{
for(int x = 0; x < numElements; x++)
{
int max = srcArray[x];
int maxIndex = x;
int hold;

for(int y = x + 1; y < numElements; y++)
{
if(srcArray[y] > max)
{
max = srcArray[y];
maxIndex = y;
}
}

hold = srcArray[x];
srcArray[x] = max;
srcArray[maxIndex] = hold;
hold = 0;

}
}

请告诉我如何解决这个问题,我一直在理论化,但我似乎无法找到可行的解决方案。

最佳答案

计算计数数组中的频率后。

std::array<std::pair<char, int>, 26> pairArray;
for (int i = 0; i < 26; ++i)
{
pairArray[i] = std::make_pair('a' + i, count[i]);
}

std::sort(pairArray.begin(), pairArray.end(), myCompare);

for (int i = 0; i < 26; ++i)
std::cout << pairArray[i].first << ": " << pairArray[i].second << std::endl;

对于myCompare

bool myCompare(const std::pair<char, int>& p1, const std::pair<char, int>& p2)
{
return p1.second > p2.second;
}

这应该按降序对数组进行排序。

关于c++ - 如何在排序时保持数组的位置相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47545253/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com