Faster way to sort an array of structs c++

2019-09-22 02:38发布

问题:

I have a struct called count declared called count with two things in it, an int called frequency and a string called word. To simplify, my program takes in a book as a text file and I count how many times each word appears. I have an array of structs and I have my program to where it will count each time a word appears and now I want a faster way to sort the array by top frequency than the way I have below. I used the bubble sorting algorithm below but it is taking my code way too long to run using this method. Any other suggestions or help would be welcome!! I have looked up sort from the algorithm library but don't understand how I would use it here. I am new to c++ so lots of explanation on how to use sort would help a lot.

void sortArray(struct count array[],int size)
{
    int cur_pos = 0;
    string the_word;
    bool flag= true;

    for(int i=0; i<(size); i++)
    {
        flag = false;
        for(int j=0; j< (size); j++)
        {
            if((array[j+1].frequency)>(array[j].frequency))
            {
                cur_pos = array[j].frequency;
                the_word = array[j].word;
                array[j].frequency = array[j+1].frequency;
                array[j].word = array[j+1].word;
                array[j+1].frequency = cur_pos;
                array[j+1].word = the_word;
                flag = true;
            }
        }
    }
};

回答1:

You just need to define operator less for your structures, and use std::sort, see example:

http://en.wikipedia.org/wiki/Sort_%28C%2B%2B%29



回答2:

After you created a pair of for the data set, you can use std::map as container and insert the pairs into it. If you want to sort according to frequency define std:map as follows

std::map myMap; myMap.insert(std::make_pair(frequency,word));

std::map is internally using a binary tree so you will get a sorted data when you retrieve it.