首先按频率对字符串中的字符进行排序,然后按字母顺序排序

mak*_*kki 4 c++ sorting vector character frequency

给定一个字符串,我试图计算字符串中每个字母的出现次数,然后将它们的频率从最高到最低排序.然后,对于具有相似出现次数的字母,我必须按字母顺序对它们进行排序.

以下是我迄今为止所做的事情:

  • 我创建了一个int大小为26 的数组,对应于26个字母的字母,各个值表示它在句子中出现的次数
  • 我把这个数组的内容推送到了一对的矢量v,intchar(int对于频率和char实际的字母)
  • 我使用了这对对矢量 std::sort(v.begin(), v.end());

在显示频率计数时,我只使用从最后一个索引开始的for循环来显示从最高到最低的结果.但是,对于那些具有相似频率的字母,我遇到了问题,因为我需要按字母顺序显示它们.我尝试使用嵌套的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 . . .
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,如果不是因为不正确的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;
}
Run Code Online (Sandbox Code Playgroud)

Man*_*726 5

您可以通过两个步骤简化这一过程:

  1. 首先使用映射来计算字符串中每个字符的出现次数:

    std::unordered_map<char, unsigned int> count;
    
    for( char character : string )
        count[character]++;
    
    Run Code Online (Sandbox Code Playgroud)
  2. 使用该地图的值作为比较条件:

    std::sort( std::begin( string ) , std::end( string ) , 
               [&]( char lhs , char rhs )
               {
                   return count[lhs] < count[rhs];
               }
             ); 
    
    Run Code Online (Sandbox Code Playgroud)

是一个在ideone上运行的工作示例.