这是我目前所做的:
- 我创建了一个大小为26的int数组,对应于字母表中的26个字母,其各自的值表示它在句子中出现的次数。 - 我将此数组的内容推入一个包含int和char(频率和实际字母)的pair的vector v中。 - 我使用`std::sort(v.begin(), v.end());`来对这个pair的vector进行排序。
在显示频率计数时,我只使用了一个for循环,从最后一个索引开始,以从高到低的顺序显示结果。然而,对于那些具有相似频率的字母,我遇到了问题,因为我需要按字母顺序显示它们。我尝试使用内层循环,内层循环从最低索引开始,并使用条件语句检查其频率是否与外层循环相同。这似乎有效,但我的问题是我无法控制这些循环,以避免冗余输出。请看下面的示例输出,以理解我的意思:
Enter a string: hello world
Pushing the array into a vector pair v:
d = 1
e = 1
h = 1
l = 3
o = 2
r = 1
w = 1
Sorted first according to frequency then alphabetically:
l = 3
o = 2
d = 1
e = 1
h = 1
r = 1
w = 1
d = 1
e = 1
h = 1
r = 1
d = 1
e = 1
h = 1
d = 1
e = 1
d = 1
Press any key to continue . . .
正如您所见,如果不是由于错误的for循环导致的冗余输出,那么一切都将是完美的。
如果您能就我的问题提供更有效或更好的实现建议,我将非常感激,只要它们不太复杂或过于先进,因为我只是一个C++初学者。
如果您需要查看我的代码,请参阅下面:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
cout<<"Enter a string: ";
string input;
getline(cin, input);
int letters[26]= {0};
for (int x = 0; x < input.length(); x++) {
if (isalpha(input[x])) {
int c = tolower(input[x] - 'a');
letters[c]++;
}
}
cout<<"\nPushing the array into a vector pair v: \n";
vector<pair<int, char> > v;
for (int x = 0; x < 26; x++) {
if (letters[x] > 0) {
char c = x + 'a';
cout << c << " = " << letters[x] << "\n";
v.push_back(std::make_pair(letters[x], c));
}
}
// Sort the vector of pairs.
std::sort(v.begin(), v.end());
// I need help here!
cout<<"\n\nSorted first according to frequency then alphabetically: \n";
for (int x = v.size() - 1 ; x >= 0; x--) {
for (int y = 0; y < x; y++) {
if (v[x].first == v[y].first) {
cout << v[y].second<< " = " << v[y].first<<endl;
}
}
cout << v[x].second<< " = " << v[x].first<<endl;
}
system("pause");
return 0;
}
map<char, int>
。 - Gabriel L.